From nobody Fri Mar 29 14:38:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) client-ip=66.175.222.12; envelope-from=bounce+27952+63380+1787277+3901457@groups.io; helo=web01.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+63380+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=intel.com ARC-Seal: i=1; a=rsa-sha256; t=1595903472; cv=none; d=zohomail.com; s=zohoarc; b=CqsqFEAPZZnTsz+9V0SHvhQzsJG0jQk7ZHHTjqjQViWSgI2+503JyKh+1vMC+IhpYv+v2FztJAswofXcQLo305lBdldl5BuiMWXvrbFB1C3X/ZUtW4Hx2Y9oG+5arE+g7d4R8F4cAMrxpq/c04rqoHH9JPYd29nnDeJlft8N2f0= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1595903472; h=Content-Transfer-Encoding:Cc:Date:From:List-Id:List-Unsubscribe:MIME-Version:Message-ID:Reply-To:Sender:Subject:To; bh=iwYhuy/VAuUcWcBusWlerP/zAtSn3zIsv7NNFlJrqQ0=; b=RGUrWqg3p394Hf6Gbg/99SeGWpnKHpIgQ3E0shlIzgTj9/0lP0W3G091/KsmNe1vK8Rar/CEsTYGp0gQlvC1d7wIyw/kUtU4trmTX2ggv9+NWRcAP32W19gVDxPGK6BFLts2CajEVDedMSSTyUAePDpwbjyTJBOuHrsEgS4xyeg= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+63380+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from web01.groups.io (web01.groups.io [66.175.222.12]) by mx.zohomail.com with SMTPS id 1595903472390931.915859059338; Mon, 27 Jul 2020 19:31:12 -0700 (PDT) Return-Path: X-Received: by 127.0.0.2 with SMTP id CwT7YY1788612xyOkAquKra9; Mon, 27 Jul 2020 19:31:12 -0700 X-Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) by mx.groups.io with SMTP id smtpd.web10.4082.1595903470937459374 for ; Mon, 27 Jul 2020 19:31:11 -0700 IronPort-SDR: 1AqARoNgl5xbA9MmziT2TYsLnRM9mMXY5zRovVMHu7ylmSoqOveZlrQ1n5oMrivb6AElWY2YAM 9oL73CZaCq7g== X-IronPort-AV: E=McAfee;i="6000,8403,9695"; a="215670618" X-IronPort-AV: E=Sophos;i="5.75,404,1589266800"; d="scan'208";a="215670618" X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-Received: from fmsmga004.fm.intel.com ([10.253.24.48]) by orsmga105.jf.intel.com with ESMTP/TLS/ECDHE-RSA-AES256-GCM-SHA384; 27 Jul 2020 19:31:08 -0700 IronPort-SDR: JfeAuHKgpxkITRH6rKQk41AyphoSKi90v79R9dDVKyUCVQoTcBLNoOZFOtgMn9vqLbSPW3jZtp 77vWK1tBbg9A== X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.75,404,1589266800"; d="scan'208";a="312439734" X-Received: from ray-dev.ccr.corp.intel.com ([10.239.158.87]) by fmsmga004.fm.intel.com with ESMTP; 27 Jul 2020 19:31:04 -0700 From: "Ni, Ray" To: devel@edk2.groups.io Cc: Michael D Kinney , Ming Shao , Eric Dong , Laszlo Ersek , Sean Brogan , Bret Barkelew , Jiewen Yao Subject: [edk2-devel] [PATCH v3] UefiCpuPkg/MtrrLib/UnitTest: Add host based unit test Date: Tue, 28 Jul 2020 10:30:07 +0800 Message-Id: <20200728023007.610-1-ray.ni@intel.com> MIME-Version: 1.0 Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,ray.ni@intel.com X-Gm-Message-State: kHbeVjNEzMKo2oLDT3FguBH5x1787277AA= Content-Transfer-Encoding: quoted-printable DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1595903472; bh=fjN60Gh23w82w4E9TlKeeUUu8dJ0ljnxFoBAEJnP0QQ=; h=Cc:Date:From:Reply-To:Subject:To; b=sgTI7AU7sgRHtLKUxVoXhz2m8gfOcbwgFr7vyNaOfYGDOC/i2rOfEGluaVw9CP01Iul YZHyc1lY2QZug3lA3AgtfgLgDqIkkK6Ik+0EphuDdVklYsMZgLjZgtmoG4gWJHegYirDy kxOMQnI388wByJMe+oo/iUnwj2VO3GLnzIQ= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Type: text/plain; charset="utf-8" Add host based unit tests for the MtrrLib services. The BaseLib services AsmCpuid(), AsmReadMsr64(), and AsmWriteMsr64() are hooked and provide simple emulation of the CPUID leafs and MSRs required by the MtrrLib to run as a host based unit test. Test cases are developed for each of the API. For the most important APIs MtrrSetMemoryAttributesInMtrrSettings() and MtrrSetMemoryAttributeInMtrrSettings(), random inputs are generated and fed to the APIs to make sure the implementation is good. The test application accepts an optional parameter which specifies how many iterations of feeding random inputs to the two APIs. The overall number of test cases increases when the iteration increases. Default iteration is 10 when no parameter is specified. Signed-off-by: Ray Ni Signed-off-by: Michael D Kinney Signed-off-by: Ming Shao Cc: Michael D Kinney Cc: Eric Dong Cc: Laszlo Ersek Cc: Ming Shao Cc: Sean Brogan Cc: Bret Barkelew Cc: Jiewen Yao Acked-by: Laszlo Ersek --- .../MtrrLib/UnitTest/MtrrLibUnitTest.c | 1140 +++++++++++++++++ .../MtrrLib/UnitTest/MtrrLibUnitTest.h | 171 +++ .../MtrrLib/UnitTest/MtrrLibUnitTestHost.inf | 39 + UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c | 913 +++++++++++++ UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc | 31 + UefiCpuPkg/UefiCpuPkg.ci.yaml | 12 +- 6 files changed, 2305 insertions(+), 1 deletion(-) create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTestHost= .inf create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c create mode 100644 UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c b/UefiCp= uPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c new file mode 100644 index 0000000000..2eac41fc74 --- /dev/null +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c @@ -0,0 +1,1140 @@ +/** @file + Unit tests of the MtrrLib instance of the MtrrLib class + + Copyright (c) 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "MtrrLibUnitTest.h" + +STATIC CONST MTRR_LIB_SYSTEM_PARAMETER mDefaultSystemParameter =3D { + 42, TRUE, TRUE, CacheUncacheable, 12 +}; + +STATIC MTRR_LIB_SYSTEM_PARAMETER mSystemParameters[] =3D { + { 38, TRUE, TRUE, CacheUncacheable, 12 }, + { 38, TRUE, TRUE, CacheWriteBack, 12 }, + { 38, TRUE, TRUE, CacheWriteThrough, 12 }, + { 38, TRUE, TRUE, CacheWriteProtected, 12 }, + { 38, TRUE, TRUE, CacheWriteCombining, 12 }, + + { 42, TRUE, TRUE, CacheUncacheable, 12 }, + { 42, TRUE, TRUE, CacheWriteBack, 12 }, + { 42, TRUE, TRUE, CacheWriteThrough, 12 }, + { 42, TRUE, TRUE, CacheWriteProtected, 12 }, + { 42, TRUE, TRUE, CacheWriteCombining, 12 }, + + { 48, TRUE, TRUE, CacheUncacheable, 12 }, + { 48, TRUE, TRUE, CacheWriteBack, 12 }, + { 48, TRUE, TRUE, CacheWriteThrough, 12 }, + { 48, TRUE, TRUE, CacheWriteProtected, 12 }, + { 48, TRUE, TRUE, CacheWriteCombining, 12 }, +}; + +UINT32 mFixedMtrrsIndex[] =3D { + MSR_IA32_MTRR_FIX64K_00000, + MSR_IA32_MTRR_FIX16K_80000, + MSR_IA32_MTRR_FIX16K_A0000, + MSR_IA32_MTRR_FIX4K_C0000, + MSR_IA32_MTRR_FIX4K_C8000, + MSR_IA32_MTRR_FIX4K_D0000, + MSR_IA32_MTRR_FIX4K_D8000, + MSR_IA32_MTRR_FIX4K_E0000, + MSR_IA32_MTRR_FIX4K_E8000, + MSR_IA32_MTRR_FIX4K_F0000, + MSR_IA32_MTRR_FIX4K_F8000 +}; +STATIC_ASSERT ( + (ARRAY_SIZE (mFixedMtrrsIndex) =3D=3D MTRR_NUMBER_OF_FIXED_MTRR), + "gFixedMtrrIndex does NOT contain all the fixed MTRRs!" + ); + +// +// Context structure to be used for most of the test cases. +// +typedef struct { + CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter; +} MTRR_LIB_TEST_CONTEXT; + +// +// Context structure to be used for GetFirmwareVariableMtrrCount() test. +// +typedef struct { + UINT32 NumberOfReservedVariableMtrrs; + CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter; +} MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT; + +STATIC CHAR8 *mCacheDescription[] =3D { "UC", "WC", "N/A", "N/A", "WT", "W= P", "WB" }; + +/** + Compare the actual memory ranges against expected memory ranges and retu= rn PASS when they match. + + @param ExpectedMemoryRanges Expected memory ranges. + @param ExpectedMemoryRangeCount Count of expected memory ranges. + @param ActualRanges Actual memory ranges. + @param ActualRangeCount Count of actual memory ranges. + + @retval UNIT_TEST_PASSED Test passed. + @retval others Test failed. +**/ +UNIT_TEST_STATUS +VerifyMemoryRanges ( + IN MTRR_MEMORY_RANGE *ExpectedMemoryRanges, + IN UINTN ExpectedMemoryRangeCount, + IN MTRR_MEMORY_RANGE *ActualRanges, + IN UINTN ActualRangeCount + ) +{ + UINTN Index; + UT_ASSERT_EQUAL (ExpectedMemoryRangeCount, ActualRangeCount); + for (Index =3D 0; Index < ExpectedMemoryRangeCount; Index++) { + UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].BaseAddress, ActualRanges= [Index].BaseAddress); + UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].Length, ActualRanges[Inde= x].Length); + UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].Type, ActualRanges[Index]= .Type); + } + + return UNIT_TEST_PASSED; +} + +/** + Dump the memory ranges. + + @param Ranges Memory ranges to dump. + @param RangeCount Count of memory ranges. +**/ +VOID +DumpMemoryRanges ( + MTRR_MEMORY_RANGE *Ranges, + UINTN RangeCount + ) +{ + UINTN Index; + for (Index =3D 0; Index < RangeCount; Index++) { + UT_LOG_INFO ("\t{ 0x%016llx, 0x%016llx, %a },\n", Ranges[Index].BaseAd= dress, Ranges[Index].Length, mCacheDescription[Ranges[Index].Type]); + } +} + +/** +**/ + +/** + Generate random count of MTRRs for each cache type. + + @param TotalCount Total MTRR count. + @param UcCount Return count of Uncacheable type. + @param WtCount Return count of Write Through type. + @param WbCount Return count of Write Back type. + @param WpCount Return count of Write Protected type. + @param WcCount Return count of Write Combining type. +**/ +VOID +GenerateRandomMemoryTypeCombination ( + IN UINT32 TotalCount, + OUT UINT32 *UcCount, + OUT UINT32 *WtCount, + OUT UINT32 *WbCount, + OUT UINT32 *WpCount, + OUT UINT32 *WcCount + ) +{ + UINTN Index; + UINT32 TotalMtrrCount; + UINT32 *CountPerType[5]; + + CountPerType[0] =3D UcCount; + CountPerType[1] =3D WtCount; + CountPerType[2] =3D WbCount; + CountPerType[3] =3D WpCount; + CountPerType[4] =3D WcCount; + + // + // Initialize the count of each cache type to 0. + // + for (Index =3D 0; Index < ARRAY_SIZE (CountPerType); Index++) { + *(CountPerType[Index]) =3D 0; + } + + // + // Pick a random count of MTRRs + // + TotalMtrrCount =3D Random32 (1, TotalCount); + for (Index =3D 0; Index < TotalMtrrCount; Index++) { + // + // For each of them, pick a random cache type. + // + (*(CountPerType[Random32 (0, ARRAY_SIZE (CountPerType) - 1)]))++; + } +} + +/** + Unit test of MtrrLib service MtrrSetMemoryAttribute() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrSetMemoryAttributesInMtrrSettings ( + IN UNIT_TEST_CONTEXT Context + ) +{ + CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter; + RETURN_STATUS Status; + UINT32 UcCount; + UINT32 WtCount; + UINT32 WbCount; + UINT32 WpCount; + UINT32 WcCount; + + UINT32 MtrrIndex; + UINT8 *Scratch; + UINTN ScratchSize; + MTRR_SETTINGS LocalMtrrs; + + MTRR_MEMORY_RANGE RawMtrrRange[MTRR_NUMBER_OF_VARIABLE_MTR= R]; + MTRR_MEMORY_RANGE ExpectedMemoryRanges[MTRR_NUMBER_OF_FIXE= D_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1]; + UINT32 ExpectedVariableMtrrUsage; + UINTN ExpectedMemoryRangesCount; + + MTRR_MEMORY_RANGE ActualMemoryRanges[MTRR_NUMBER_OF_FIXED_= MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1]; + UINT32 ActualVariableMtrrUsage; + UINTN ActualMemoryRangesCount; + + MTRR_SETTINGS *Mtrrs[2]; + + SystemParameter =3D (MTRR_LIB_SYSTEM_PARAMETER *) Context; + GenerateRandomMemoryTypeCombination ( + SystemParameter->VariableMtrrCount - PatchPcdGet32 (PcdCpuNumberOfRese= rvedVariableMtrrs), + &UcCount, &WtCount, &WbCount, &WpCount, &WcCount + ); + GenerateValidAndConfigurableMtrrPairs ( + SystemParameter->PhysicalAddressBits, RawMtrrRange, + UcCount, WtCount, WbCount, WpCount, WcCount + ); + + ExpectedVariableMtrrUsage =3D UcCount + WtCount + WbCount + WpCount + Wc= Count; + ExpectedMemoryRangesCount =3D ARRAY_SIZE (ExpectedMemoryRanges); + GetEffectiveMemoryRanges ( + SystemParameter->DefaultCacheType, + SystemParameter->PhysicalAddressBits, + RawMtrrRange, ExpectedVariableMtrrUsage, + ExpectedMemoryRanges, &ExpectedMemoryRangesCount + ); + + UT_LOG_INFO ( + "Total MTRR [%d]: UC=3D%d, WT=3D%d, WB=3D%d, WP=3D%d, WC=3D%d\n", + ExpectedVariableMtrrUsage, UcCount, WtCount, WbCount, WpCount, WcCount + ); + UT_LOG_INFO ("--- Expected Memory Ranges [%d] ---\n", ExpectedMemoryRang= esCount); + DumpMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesCount); + + // + // Default cache type is always an INPUT + // + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); + LocalMtrrs.MtrrDefType =3D MtrrGetDefaultMemoryType (); + ScratchSize =3D SCRATCH_BUFFER_SIZE; + Mtrrs[0] =3D &LocalMtrrs; + Mtrrs[1] =3D NULL; + + for (MtrrIndex =3D 0; MtrrIndex < ARRAY_SIZE (Mtrrs); MtrrIndex++) { + Scratch =3D calloc (ScratchSize, sizeof (UINT8)); + Status =3D MtrrSetMemoryAttributesInMtrrSettings (Mtrrs[MtrrIndex], Sc= ratch, &ScratchSize, ExpectedMemoryRanges, ExpectedMemoryRangesCount); + if (Status =3D=3D RETURN_BUFFER_TOO_SMALL) { + Scratch =3D realloc (Scratch, ScratchSize); + Status =3D MtrrSetMemoryAttributesInMtrrSettings (Mtrrs[MtrrIndex], = Scratch, &ScratchSize, ExpectedMemoryRanges, ExpectedMemoryRangesCount); + } + UT_ASSERT_STATUS_EQUAL (Status, RETURN_SUCCESS); + + if (Mtrrs[MtrrIndex] =3D=3D NULL) { + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); + MtrrGetAllMtrrs (&LocalMtrrs); + } + ActualMemoryRangesCount =3D ARRAY_SIZE (ActualMemoryRanges); + CollectTestResult ( + SystemParameter->DefaultCacheType, SystemParameter->PhysicalAddressB= its, SystemParameter->VariableMtrrCount, + &LocalMtrrs, ActualMemoryRanges, &ActualMemoryRangesCount, &ActualVa= riableMtrrUsage + ); + + UT_LOG_INFO ("--- Actual Memory Ranges [%d] ---\n", ActualMemoryRanges= Count); + DumpMemoryRanges (ActualMemoryRanges, ActualMemoryRangesCount); + VerifyMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesCount, A= ctualMemoryRanges, ActualMemoryRangesCount); + UT_ASSERT_TRUE (ExpectedVariableMtrrUsage >=3D ActualVariableMtrrUsage= ); + + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); + } + + free (Scratch); + + return UNIT_TEST_PASSED; +} + +/** + Test routine to check whether invalid base/size can be rejected. + + @param Context Pointer to MTRR_LIB_SYSTEM_PARAMETER. + + @return Test status. +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestInvalidMemoryLayouts ( + IN UNIT_TEST_CONTEXT Context + ) +{ + CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter; + MTRR_MEMORY_RANGE Ranges[MTRR_NUMBER_OF_VARIABLE_MTRR * 2 = + 1]; + UINTN RangeCount; + UINT64 MaxAddress; + UINT32 Index; + UINT64 BaseAddress; + UINT64 Length; + RETURN_STATUS Status; + UINTN ScratchSize; + + SystemParameter =3D (MTRR_LIB_SYSTEM_PARAMETER *) Context; + + RangeCount =3D Random32 (1, ARRAY_SIZE (Ranges)); + MaxAddress =3D 1ull << SystemParameter->PhysicalAddressBits; + + for (Index =3D 0; Index < RangeCount; Index++) { + do { + BaseAddress =3D Random64 (0, MaxAddress); + Length =3D Random64 (1, MaxAddress - BaseAddress); + } while (((BaseAddress & 0xFFF) =3D=3D 0) || ((Length & 0xFFF) =3D=3D = 0)); + + Ranges[Index].BaseAddress =3D BaseAddress; + Ranges[Index].Length =3D Length; + Ranges[Index].Type =3D GenerateRandomCacheType (); + + Status =3D MtrrSetMemoryAttribute ( + Ranges[Index].BaseAddress, Ranges[Index].Length, Ranges[Index].Type + ); + UT_ASSERT_TRUE (RETURN_ERROR (Status)); + } + + ScratchSize =3D 0; + Status =3D MtrrSetMemoryAttributesInMtrrSettings (NULL, NULL, &ScratchSi= ze, Ranges, RangeCount); + UT_ASSERT_TRUE (RETURN_ERROR (Status)); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service IsMtrrSupported() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestIsMtrrSupported ( + IN UNIT_TEST_CONTEXT Context + ) +{ + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_LIB_TEST_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + // + // MTRR capability off in CPUID leaf. + // + SystemParameter.MtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + UT_ASSERT_FALSE (IsMtrrSupported ()); + + // + // MTRR capability on in CPUID leaf, but no variable or fixed MTRRs. + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D 0; + SystemParameter.FixedMtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + UT_ASSERT_FALSE (IsMtrrSupported ()); + + // + // MTRR capability on in CPUID leaf, but no variable MTRRs. + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D 0; + SystemParameter.FixedMtrrSupported =3D TRUE; + InitializeMtrrRegs (&SystemParameter); + UT_ASSERT_FALSE (IsMtrrSupported ()); + + // + // MTRR capability on in CPUID leaf, but no fixed MTRRs. + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D 7; + SystemParameter.FixedMtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + UT_ASSERT_FALSE (IsMtrrSupported ()); + + // + // MTRR capability on in CPUID leaf with both variable and fixed MTRRs. + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D 7; + SystemParameter.FixedMtrrSupported =3D TRUE; + InitializeMtrrRegs (&SystemParameter); + UT_ASSERT_TRUE (IsMtrrSupported ()); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service GetVariableMtrrCount() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestGetVariableMtrrCount ( + IN UNIT_TEST_CONTEXT Context + ) +{ + UINT32 Result; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_LIB_TEST_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + // + // If MTRR capability off in CPUID leaf, then the count is always 0. + // + SystemParameter.MtrrSupported =3D FALSE; + for (SystemParameter.VariableMtrrCount =3D 1; SystemParameter.VariableMt= rrCount <=3D MTRR_NUMBER_OF_VARIABLE_MTRR; SystemParameter.VariableMtrrCoun= t++) { + InitializeMtrrRegs (&SystemParameter); + Result =3D GetVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, 0); + } + + // + // Try all supported variable MTRR counts. + // If variable MTRR count is > MTRR_NUMBER_OF_VARIABLE_MTRR, then an ASS= ERT() + // is generated. + // + SystemParameter.MtrrSupported =3D TRUE; + for (SystemParameter.VariableMtrrCount =3D 1; SystemParameter.VariableMt= rrCount <=3D MTRR_NUMBER_OF_VARIABLE_MTRR; SystemParameter.VariableMtrrCoun= t++) { + InitializeMtrrRegs (&SystemParameter); + Result =3D GetVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, SystemParameter.VariableMtrrCount); + } + + // + // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER_OF_VARIABLE_M= TRR + // + SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE_MTRR + 1; + InitializeMtrrRegs (&SystemParameter); + UT_EXPECT_ASSERT_FAILURE (GetVariableMtrrCount (), NULL); + + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D MAX_UINT8; + InitializeMtrrRegs (&SystemParameter); + UT_EXPECT_ASSERT_FAILURE (GetVariableMtrrCount (), NULL); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service GetFirmwareVariableMtrrCount() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestGetFirmwareVariableMtrrCount ( + IN UNIT_TEST_CONTEXT Context + ) +{ + UINT32 Result; + UINT32 ReservedMtrrs; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *) C= ontext; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + + InitializeMtrrRegs (&SystemParameter); + // + // Positive test cases for VCNT =3D 10 and Reserved PCD in range 0..10 + // + for (ReservedMtrrs =3D 0; ReservedMtrrs <=3D SystemParameter.VariableMtr= rCount; ReservedMtrrs++) { + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, ReservedMtrrs); + Result =3D GetFirmwareVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, SystemParameter.VariableMtrrCount - ReservedM= trrs); + } + + // + // Negative test cases when Reserved PCD is larger than VCNT + // + for (ReservedMtrrs =3D SystemParameter.VariableMtrrCount + 1; ReservedMt= rrs <=3D 255; ReservedMtrrs++) { + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, ReservedMtrrs); + Result =3D GetFirmwareVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, 0); + } + + // + // Negative test cases when Reserved PCD is larger than VCNT + // + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, MAX_UINT32); + Result =3D GetFirmwareVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, 0); + + // + // Negative test case when MTRRs are not supported + // + SystemParameter.MtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, 2); + Result =3D GetFirmwareVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, 0); + + // + // Negative test case when Fixed MTRRs are not supported + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.FixedMtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, 2); + Result =3D GetFirmwareVariableMtrrCount (); + UT_ASSERT_EQUAL (Result, 0); + + // + // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER_OF_VARIABLE_M= TRR + // + SystemParameter.FixedMtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE_MTRR + 1; + InitializeMtrrRegs (&SystemParameter); + UT_EXPECT_ASSERT_FAILURE (GetFirmwareVariableMtrrCount (), NULL); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrGetMemoryAttribute() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrGetMemoryAttribute ( + IN UNIT_TEST_CONTEXT Context + ) +{ + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrGetFixedMtrr() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrGetFixedMtrr ( + IN UNIT_TEST_CONTEXT Context + ) +{ + MTRR_FIXED_SETTINGS *Result; + MTRR_FIXED_SETTINGS ExpectedFixedSettings; + MTRR_FIXED_SETTINGS FixedSettings; + UINTN Index; + UINTN MsrIndex; + UINTN ByteIndex; + UINT64 MsrValue; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_LIB_TEST_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + InitializeMtrrRegs (&SystemParameter); + // + // Set random cache type to different ranges under 1MB and make sure + // the fixed MTRR settings are expected. + // Try 100 times. + // + for (Index =3D 0; Index < 100; Index++) { + for (MsrIndex =3D 0; MsrIndex < ARRAY_SIZE (mFixedMtrrsIndex); MsrInde= x++) { + MsrValue =3D 0; + for (ByteIndex =3D 0; ByteIndex < sizeof (UINT64); ByteIndex++) { + MsrValue =3D MsrValue | LShiftU64 (GenerateRandomCacheType (), Byt= eIndex * 8); + } + ExpectedFixedSettings.Mtrr[MsrIndex] =3D MsrValue; + AsmWriteMsr64 (mFixedMtrrsIndex[MsrIndex], MsrValue); + } + + Result =3D MtrrGetFixedMtrr (&FixedSettings); + UT_ASSERT_EQUAL (Result, &FixedSettings); + UT_ASSERT_MEM_EQUAL (&FixedSettings, &ExpectedFixedSettings, sizeof (F= ixedSettings)); + } + + // + // Negative test case when MTRRs are not supported + // + SystemParameter.MtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + + ZeroMem (&FixedSettings, sizeof (FixedSettings)); + ZeroMem (&ExpectedFixedSettings, sizeof (ExpectedFixedSettings)); + Result =3D MtrrGetFixedMtrr (&FixedSettings); + UT_ASSERT_EQUAL (Result, &FixedSettings); + UT_ASSERT_MEM_EQUAL (&ExpectedFixedSettings, &FixedSettings, sizeof (Exp= ectedFixedSettings)); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrGetAllMtrrs() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrGetAllMtrrs ( + IN UNIT_TEST_CONTEXT Context + ) +{ + MTRR_SETTINGS *Result; + MTRR_SETTINGS Mtrrs; + MTRR_SETTINGS ExpectedMtrrs; + MTRR_VARIABLE_SETTING VariableMtrr[MTRR_NUMBER_OF_VARIABLE_MTRR]; + UINT32 Index; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_LIB_TEST_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + InitializeMtrrRegs (&SystemParameter); + + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++) { + GenerateRandomMtrrPair (SystemParameter.PhysicalAddressBits, GenerateR= andomCacheType (), &VariableMtrr[Index], NULL); + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index << 1), VariableMtrr[In= dex].Base); + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index << 1), VariableMtrr[In= dex].Mask); + } + Result =3D MtrrGetAllMtrrs (&Mtrrs); + UT_ASSERT_EQUAL (Result, &Mtrrs); + UT_ASSERT_MEM_EQUAL (Mtrrs.Variables.Mtrr, VariableMtrr, sizeof (MTRR_VA= RIABLE_SETTING) * SystemParameter.VariableMtrrCount); + + // + // Negative test case when MTRRs are not supported + // + ZeroMem (&ExpectedMtrrs, sizeof (ExpectedMtrrs)); + ZeroMem (&Mtrrs, sizeof (Mtrrs)); + + SystemParameter.MtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + Result =3D MtrrGetAllMtrrs (&Mtrrs); + UT_ASSERT_EQUAL (Result, &Mtrrs); + UT_ASSERT_MEM_EQUAL (&ExpectedMtrrs, &Mtrrs, sizeof (ExpectedMtrrs)); + + // + // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER_OF_VARIABLE_M= TRR + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE_MTRR + 1; + InitializeMtrrRegs (&SystemParameter); + UT_EXPECT_ASSERT_FAILURE (MtrrGetAllMtrrs (&Mtrrs), NULL); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrSetAllMtrrs() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrSetAllMtrrs ( + IN UNIT_TEST_CONTEXT Context + ) +{ + MTRR_SETTINGS *Result; + MTRR_SETTINGS Mtrrs; + UINT32 Index; + MSR_IA32_MTRR_DEF_TYPE_REGISTER Default; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_LIB_TEST_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + InitializeMtrrRegs (&SystemParameter); + + Default.Uint64 =3D 0; + Default.Bits.E =3D 1; + Default.Bits.FE =3D 1; + Default.Bits.Type =3D GenerateRandomCacheType (); + + ZeroMem (&Mtrrs, sizeof (Mtrrs)); + Mtrrs.MtrrDefType =3D Default.Uint64; + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++) { + GenerateRandomMtrrPair (SystemParameter.PhysicalAddressBits, GenerateR= andomCacheType (), &Mtrrs.Variables.Mtrr[Index], NULL); + } + Result =3D MtrrSetAllMtrrs (&Mtrrs); + UT_ASSERT_EQUAL (Result, &Mtrrs); + + UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE), Mtrrs.MtrrDefTyp= e); + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++) { + UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index << 1))= , Mtrrs.Variables.Mtrr[Index].Base); + UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index << 1))= , Mtrrs.Variables.Mtrr[Index].Mask); + } + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrGetMemoryAttributeInVariableMtrr() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrGetMemoryAttributeInVariableMtrr ( + IN UNIT_TEST_CONTEXT Context + ) +{ + MTRR_LIB_TEST_CONTEXT *LocalContext; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + UINT32 Result; + MTRR_VARIABLE_SETTING VariableSetting[MTRR_NUMBER_OF_VARIABLE_= MTRR]; + VARIABLE_MTRR VariableMtrr[MTRR_NUMBER_OF_VARIABLE_MTR= R]; + UINT64 ValidMtrrBitsMask; + UINT64 ValidMtrrAddressMask; + UINT32 Index; + MSR_IA32_MTRR_PHYSBASE_REGISTER Base; + MSR_IA32_MTRR_PHYSMASK_REGISTER Mask; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + + InitializeMtrrRegs (&SystemParameter); + + ValidMtrrBitsMask =3D (1ull << SystemParameter.PhysicalAddressBits) -= 1; + ValidMtrrAddressMask =3D ValidMtrrBitsMask & 0xfffffffffffff000ULL; + + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++) { + GenerateRandomMtrrPair (SystemParameter.PhysicalAddressBits, GenerateR= andomCacheType (), &VariableSetting[Index], NULL); + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index << 1), VariableSetting= [Index].Base); + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index << 1), VariableSetting= [Index].Mask); + } + Result =3D MtrrGetMemoryAttributeInVariableMtrr (ValidMtrrBitsMask, Vali= dMtrrAddressMask, VariableMtrr); + UT_ASSERT_EQUAL (Result, SystemParameter.VariableMtrrCount); + + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++) { + Base.Uint64 =3D VariableMtrr[Index].BaseAddress; + Base.Bits.Type =3D (UINT32) VariableMtrr[Index].Type; + UT_ASSERT_EQUAL (Base.Uint64, VariableSetting[Index].Base); + + Mask.Uint64 =3D ~(VariableMtrr[Index].Length - 1) & ValidMtrrBitsMa= sk; + Mask.Bits.V =3D 1; + UT_ASSERT_EQUAL (Mask.Uint64, VariableSetting[Index].Mask); + } + + // + // Negative test case when MTRRs are not supported + // + SystemParameter.MtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + Result =3D MtrrGetMemoryAttributeInVariableMtrr (ValidMtrrBitsMask, Vali= dMtrrAddressMask, VariableMtrr); + UT_ASSERT_EQUAL (Result, 0); + + // + // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER_OF_VARIABLE_M= TRR + // + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE_MTRR + 1; + InitializeMtrrRegs (&SystemParameter); + UT_EXPECT_ASSERT_FAILURE (MtrrGetMemoryAttributeInVariableMtrr (ValidMtr= rBitsMask, ValidMtrrAddressMask, VariableMtrr), NULL); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrDebugPrintAllMtrrs() + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrDebugPrintAllMtrrs ( + IN UNIT_TEST_CONTEXT Context + ) +{ + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrGetDefaultMemoryType(). + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrGetDefaultMemoryType ( + IN UNIT_TEST_CONTEXT Context + ) +{ + MTRR_LIB_TEST_CONTEXT *LocalContext; + UINTN Index; + MTRR_MEMORY_CACHE_TYPE Result; + MTRR_LIB_SYSTEM_PARAMETER SystemParameter; + MTRR_MEMORY_CACHE_TYPE CacheType[5]; + + CacheType[0] =3D CacheUncacheable; + CacheType[1] =3D CacheWriteCombining; + CacheType[2] =3D CacheWriteThrough; + CacheType[3] =3D CacheWriteProtected; + CacheType[4] =3D CacheWriteBack; + + LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context; + + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (System= Parameter)); + // + // If MTRRs are supported, then always return the cache type in the MSR + // MSR_IA32_MTRR_DEF_TYPE + // + for (Index =3D 0; Index < ARRAY_SIZE (CacheType); Index++) { + SystemParameter.DefaultCacheType =3D CacheType[Index]; + InitializeMtrrRegs (&SystemParameter); + Result =3D MtrrGetDefaultMemoryType (); + UT_ASSERT_EQUAL (Result, SystemParameter.DefaultCacheType); + } + + // + // If MTRRs are not supported, then always return CacheUncacheable + // + SystemParameter.MtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + Result =3D MtrrGetDefaultMemoryType (); + UT_ASSERT_EQUAL (Result, CacheUncacheable); + + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.FixedMtrrSupported =3D FALSE; + InitializeMtrrRegs (&SystemParameter); + Result =3D MtrrGetDefaultMemoryType (); + UT_ASSERT_EQUAL (Result, CacheUncacheable); + + SystemParameter.MtrrSupported =3D TRUE; + SystemParameter.FixedMtrrSupported =3D TRUE; + SystemParameter.VariableMtrrCount =3D 0; + InitializeMtrrRegs (&SystemParameter); + Result =3D MtrrGetDefaultMemoryType (); + UT_ASSERT_EQUAL (Result, CacheUncacheable); + + return UNIT_TEST_PASSED; +} + +/** + Unit test of MtrrLib service MtrrSetMemoryAttributeInMtrrSettings(). + + @param[in] Context Ignored + + @retval UNIT_TEST_PASSED The Unit test has completed and th= e test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. + +**/ +UNIT_TEST_STATUS +EFIAPI +UnitTestMtrrSetMemoryAttributeInMtrrSettings ( + IN UNIT_TEST_CONTEXT Context + ) +{ + CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter; + RETURN_STATUS Status; + UINT32 UcCount; + UINT32 WtCount; + UINT32 WbCount; + UINT32 WpCount; + UINT32 WcCount; + + UINTN MtrrIndex; + UINTN Index; + MTRR_SETTINGS LocalMtrrs; + + MTRR_MEMORY_RANGE RawMtrrRange[MTRR_NUMBER_OF_VARIABLE_MTR= R]; + MTRR_MEMORY_RANGE ExpectedMemoryRanges[MTRR_NUMBER_OF_FIXE= D_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1]; + UINT32 ExpectedVariableMtrrUsage; + UINTN ExpectedMemoryRangesCount; + + MTRR_MEMORY_RANGE ActualMemoryRanges[MTRR_NUMBER_OF_FIXED_= MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1]; + UINT32 ActualVariableMtrrUsage; + UINTN ActualMemoryRangesCount; + + MTRR_SETTINGS *Mtrrs[2]; + + SystemParameter =3D (MTRR_LIB_SYSTEM_PARAMETER *) Context; + GenerateRandomMemoryTypeCombination ( + SystemParameter->VariableMtrrCount - PatchPcdGet32 (PcdCpuNumberOfRese= rvedVariableMtrrs), + &UcCount, &WtCount, &WbCount, &WpCount, &WcCount + ); + GenerateValidAndConfigurableMtrrPairs ( + SystemParameter->PhysicalAddressBits, RawMtrrRange, + UcCount, WtCount, WbCount, WpCount, WcCount + ); + + ExpectedVariableMtrrUsage =3D UcCount + WtCount + WbCount + WpCount + Wc= Count; + ExpectedMemoryRangesCount =3D ARRAY_SIZE (ExpectedMemoryRanges); + GetEffectiveMemoryRanges ( + SystemParameter->DefaultCacheType, + SystemParameter->PhysicalAddressBits, + RawMtrrRange, ExpectedVariableMtrrUsage, + ExpectedMemoryRanges, &ExpectedMemoryRangesCount + ); + + UT_LOG_INFO ("--- Expected Memory Ranges [%d] ---\n", ExpectedMemoryRang= esCount); + DumpMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesCount); + // + // Default cache type is always an INPUT + // + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); + LocalMtrrs.MtrrDefType =3D MtrrGetDefaultMemoryType (); + Mtrrs[0] =3D &LocalMtrrs; + Mtrrs[1] =3D NULL; + + for (MtrrIndex =3D 0; MtrrIndex < ARRAY_SIZE (Mtrrs); MtrrIndex++) { + for (Index =3D 0; Index < ExpectedMemoryRangesCount; Index++) { + Status =3D MtrrSetMemoryAttributeInMtrrSettings ( + Mtrrs[MtrrIndex], + ExpectedMemoryRanges[Index].BaseAddress, + ExpectedMemoryRanges[Index].Length, + ExpectedMemoryRanges[Index].Type + ); + UT_ASSERT_TRUE (Status =3D=3D RETURN_SUCCESS || Status =3D=3D RETURN= _OUT_OF_RESOURCES || Status =3D=3D RETURN_BUFFER_TOO_SMALL); + if (Status =3D=3D RETURN_OUT_OF_RESOURCES || Status =3D=3D RETURN_BU= FFER_TOO_SMALL) { + return UNIT_TEST_SKIPPED; + } + } + + if (Mtrrs[MtrrIndex] =3D=3D NULL) { + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); + MtrrGetAllMtrrs (&LocalMtrrs); + } + ActualMemoryRangesCount =3D ARRAY_SIZE (ActualMemoryRanges); + CollectTestResult ( + SystemParameter->DefaultCacheType, SystemParameter->PhysicalAddressB= its, SystemParameter->VariableMtrrCount, + &LocalMtrrs, ActualMemoryRanges, &ActualMemoryRangesCount, &ActualVa= riableMtrrUsage + ); + UT_LOG_INFO ("--- Actual Memory Ranges [%d] ---\n", ActualMemoryRanges= Count); + DumpMemoryRanges (ActualMemoryRanges, ActualMemoryRangesCount); + VerifyMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesCount, A= ctualMemoryRanges, ActualMemoryRangesCount); + UT_ASSERT_TRUE (ExpectedVariableMtrrUsage >=3D ActualVariableMtrrUsage= ); + + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); + } + + return UNIT_TEST_PASSED; +} + + +/** + Prep routine for UnitTestGetFirmwareVariableMtrrCount(). + + @param Context Point to a UINT32 data to save the PcdCpuNumberOfReserve= dVariableMtrrs. +**/ +UNIT_TEST_STATUS +EFIAPI +SavePcdValue ( + UNIT_TEST_CONTEXT Context + ) +{ + MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *) C= ontext; + LocalContext->NumberOfReservedVariableMtrrs =3D PatchPcdGet32 (PcdCpuNum= berOfReservedVariableMtrrs); + return UNIT_TEST_PASSED; +} + +/** + Clean up routine for UnitTestGetFirmwareVariableMtrrCount(). + + @param Context Point to a UINT32 data to save the PcdCpuNumberOfReserve= dVariableMtrrs. +**/ +UNIT_TEST_STATUS +EFIAPI +RestorePcdValue ( + UNIT_TEST_CONTEXT Context + ) +{ + MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *LocalContext; + + LocalContext =3D (MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *) C= ontext; + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, LocalContext->Number= OfReservedVariableMtrrs); + return UNIT_TEST_PASSED; +} + +/** + Initialize the unit test framework, suite, and unit tests for the + ResetSystemLib and run the ResetSystemLib unit test. + + @param Iteration Iteration of testing MtrrSetMemoryAttribu= teInMtrrSettings + and MtrrSetMemoryAttributesInMtrrSettings= using random inputs. + + @retval EFI_SUCCESS All test cases were dispatched. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available = to + initialize the unit tests. +**/ +STATIC +EFI_STATUS +EFIAPI +UnitTestingEntry ( + UINTN Iteration + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + UNIT_TEST_SUITE_HANDLE MtrrApiTests; + UINTN Index; + UINTN SystemIndex; + MTRR_LIB_TEST_CONTEXT Context; + MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT GetFirmwareVariableMtr= rCountContext; + + Context.SystemParameter =3D &mDefaultSystemP= arameter; + GetFirmwareVariableMtrrCountContext.SystemParameter =3D &mDefaultSystemP= arameter; + Framework =3D NULL; + + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSIO= N)); + + // + // Setup the test framework for running the tests. + // + Status =3D InitUnitTestFramework (&Framework, UNIT_TEST_APP_NAME, gEfiCa= llerBaseName, UNIT_TEST_APP_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status =3D %r\n= ", Status)); + goto EXIT; + } + + // + // --------------Suite-----------Description--------------Name----------= Function--------Pre---Post-------------------Context----------- + // + + // + // Populate the MtrrLib API Unit Test Suite. + // + Status =3D CreateUnitTestSuite (&MtrrApiTests, Framework, "MtrrLib API T= ests", "MtrrLib.MtrrLib", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MtrrLib API Te= sts\n")); + Status =3D EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase (MtrrApiTests, "Test IsMtrrSupported", = "MtrrSupported", UnitTestIsMtrrSupported, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test GetVariableMtrrCount", = "GetVariableMtrrCount", UnitTestGetVariableMtrrCount, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test GetFirmwareVariableMtrrCount", = "GetFirmwareVariableMtrrCount", UnitTestGetFirmwareVariableMtrrCoun= t, SavePcdValue, RestorePcdValue, &GetFirmwareVariableMtrrCountCont= ext); + AddTestCase (MtrrApiTests, "Test MtrrGetMemoryAttribute", = "MtrrGetMemoryAttribute", UnitTestMtrrGetMemoryAttribute, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test MtrrGetFixedMtrr", = "MtrrGetFixedMtrr", UnitTestMtrrGetFixedMtrr, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test MtrrGetAllMtrrs", = "MtrrGetAllMtrrs", UnitTestMtrrGetAllMtrrs, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test MtrrSetAllMtrrs", = "MtrrSetAllMtrrs", UnitTestMtrrSetAllMtrrs, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test MtrrGetMemoryAttributeInVariableMtrr", = "MtrrGetMemoryAttributeInVariableMtrr", UnitTestMtrrGetMemoryAttributeInVar= iableMtrr, NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test MtrrDebugPrintAllMtrrs", = "MtrrDebugPrintAllMtrrs", UnitTestMtrrDebugPrintAllMtrrs, = NULL, NULL, &Context); + AddTestCase (MtrrApiTests, "Test MtrrGetDefaultMemoryType", = "MtrrGetDefaultMemoryType", UnitTestMtrrGetDefaultMemoryType, = NULL, NULL, &Context); + + for (SystemIndex =3D 0; SystemIndex < ARRAY_SIZE (mSystemParameters); Sy= stemIndex++) { + for (Index =3D 0; Index < Iteration; Index++) { + AddTestCase (MtrrApiTests, "Test InvalidMemoryLayouts", = "InvalidMemoryLayouts", UnitTestInvalidMemoryLayouts,= InitializeMtrrRegs, NULL, &mSystemParameters[SystemIndex]= ); + AddTestCase (MtrrApiTests, "Test MtrrSetMemoryAttributeInMtrrSetting= s", "MtrrSetMemoryAttributeInMtrrSettings", UnitTestMtrrSetMemoryAttribut= eInMtrrSettings, InitializeMtrrRegs, NULL, &mSystemParameters[SystemIndex]= ); + AddTestCase (MtrrApiTests, "Test MtrrSetMemoryAttributesInMtrrSettin= gs", "MtrrSetMemoryAttributesInMtrrSettings", UnitTestMtrrSetMemoryAttribut= esInMtrrSettings, InitializeMtrrRegs, NULL, &mSystemParameters[SystemIndex]= ); + } + } + // + // Execute the tests. + // + srand ((unsigned int) time (NULL)); + Status =3D RunAllTestSuites (Framework); + +EXIT: + if (Framework !=3D NULL) { + FreeUnitTestFramework (Framework); + } + + return Status; +} + +/** + Standard POSIX C entry point for host based unit test execution. + + @param Argc Number of arguments. + @param Argv Array of arguments. + + @return Test application exit code. +**/ +INT32 +main ( + INT32 Argc, + CHAR8 *Argv[] + ) +{ + UINTN Iteration; + + // + // First parameter specifies the test iterations. + // Default is 10. + // + Iteration =3D 10; + if (Argc =3D=3D 2) { + Iteration =3D atoi (Argv[1]); + } + return UnitTestingEntry (Iteration); +} diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h b/UefiCp= uPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h new file mode 100644 index 0000000000..25d4269589 --- /dev/null +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h @@ -0,0 +1,171 @@ +/** @file + + Copyright (c) 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _MTRR_SUPPORT_H_ +#define _MTRR_SUPPORT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define UNIT_TEST_APP_NAME "MtrrLib Unit Tests" +#define UNIT_TEST_APP_VERSION "1.0" + +#define SCRATCH_BUFFER_SIZE SIZE_16KB + +typedef struct { + UINT8 PhysicalAddressBits; + BOOLEAN MtrrSupported; + BOOLEAN FixedMtrrSupported; + MTRR_MEMORY_CACHE_TYPE DefaultCacheType; + UINT32 VariableMtrrCount; +} MTRR_LIB_SYSTEM_PARAMETER; + +extern UINT32 mFixedMtrrsIndex[]; + +/** + Initialize the MTRR registers. + + @param SystemParameter System parameter that controls the MTRR registers= initialization. +**/ +UNIT_TEST_STATUS +EFIAPI +InitializeMtrrRegs ( + IN MTRR_LIB_SYSTEM_PARAMETER *SystemParameter + ); + +/** + Return a random memory cache type. +**/ +MTRR_MEMORY_CACHE_TYPE +GenerateRandomCacheType ( + VOID + ); + +/** + Generate random MTRRs. + + @param PhysicalAddressBits Physical address bits. + @param RawMemoryRanges Return the randomly generated MTRRs. + @param UcCount Count of Uncacheable MTRRs. + @param WtCount Count of Write Through MTRRs. + @param WbCount Count of Write Back MTRRs. + @param WpCount Count of Write Protected MTRRs. + @param WcCount Count of Write Combining MTRRs. +**/ +VOID +GenerateValidAndConfigurableMtrrPairs ( + IN UINT32 PhysicalAddressBits, + IN OUT MTRR_MEMORY_RANGE *RawMemoryRanges, + IN UINT32 UcCount, + IN UINT32 WtCount, + IN UINT32 WbCount, + IN UINT32 WpCount, + IN UINT32 WcCount + ); + +/** + Convert the MTRR BASE/MASK array to memory ranges. + + @param DefaultType Default memory type. + @param PhysicalAddressBits Physical address bits. + @param RawMemoryRanges Raw memory ranges. + @param RawMemoryRangeCount Count of raw memory ranges. + @param MemoryRanges Memory ranges. + @param MemoryRangeCount Count of memory ranges. +**/ +VOID +GetEffectiveMemoryRanges ( + IN MTRR_MEMORY_CACHE_TYPE DefaultType, + IN UINT32 PhysicalAddressBits, + IN MTRR_MEMORY_RANGE *RawMemoryRanges, + IN UINT32 RawMemoryRangeCount, + OUT MTRR_MEMORY_RANGE *MemoryRanges, + OUT UINTN *MemoryRangeCount + ); + +/** + Generate random MTRR BASE/MASK for a specified type. + + @param PhysicalAddressBits Physical address bits. + @param CacheType Cache type. + @param MtrrPair Return the random MTRR. + @param MtrrMemoryRange Return the random memory range. +**/ +VOID +GenerateRandomMtrrPair ( + IN UINT32 PhysicalAddressBits, + IN MTRR_MEMORY_CACHE_TYPE CacheType, + OUT MTRR_VARIABLE_SETTING *MtrrPair, OPTIONAL + OUT MTRR_MEMORY_RANGE *MtrrMemoryRange OPTIONAL + ); + +/** + Collect the test result. + + @param DefaultType Default memory type. + @param PhysicalAddressBits Physical address bits. + @param VariableMtrrCount Count of variable MTRRs. + @param Mtrrs MTRR settings to collect from. + @param Ranges Return the memory ranges. + @param RangeCount Return the count of memory ranges. + @param MtrrCount Return the count of variable MTRRs being use= d. +**/ +VOID +CollectTestResult ( + IN MTRR_MEMORY_CACHE_TYPE DefaultType, + IN UINT32 PhysicalAddressBits, + IN UINT32 VariableMtrrCount, + IN MTRR_SETTINGS *Mtrrs, + OUT MTRR_MEMORY_RANGE *Ranges, + IN OUT UINTN *RangeCount, + OUT UINT32 *MtrrCount + ); + +/** + Return a 64bit random number. + + @param Start Start of the random number range. + @param Limit Limit of the random number range. + @return 64bit random number +**/ +UINT64 +Random64 ( + UINT64 Start, + UINT64 Limit + ); + +/** + Return a 32bit random number. + + @param Start Start of the random number range. + @param Limit Limit of the random number range. + @return 32bit random number +**/ +UINT32 +Random32 ( + UINT32 Start, + UINT32 Limit + ); +#endif diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTestHost.inf b/= UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTestHost.inf new file mode 100644 index 0000000000..447238dc81 --- /dev/null +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTestHost.inf @@ -0,0 +1,39 @@ +## @file +# Unit tests of the MtrrLib instance of the MtrrLib class +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION =3D 0x00010006 + BASE_NAME =3D MtrrLibUnitTestHost + FILE_GUID =3D A1542D84-B64D-4847-885E-0509084376AB + MODULE_TYPE =3D HOST_APPLICATION + VERSION_STRING =3D 1.0 + +# +# The following information is for reference only and not required by the = build tools. +# +# VALID_ARCHITECTURES =3D IA32 X64 +# + +[Sources] + MtrrLibUnitTest.c + MtrrLibUnitTest.h + Support.c + +[Packages] + MdePkg/MdePkg.dec + UefiCpuPkg/UefiCpuPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + MtrrLib + UnitTestLib + +[Pcd] + gUefiCpuPkgTokenSpaceGuid.PcdCpuNumberOfReservedVariableMtrrs ## SOMET= IMES_CONSUMES diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c b/UefiCpuPkg/Lib= rary/MtrrLib/UnitTest/Support.c new file mode 100644 index 0000000000..9fe4b0278e --- /dev/null +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c @@ -0,0 +1,913 @@ +/** @file + Unit tests of the MtrrLib instance of the MtrrLib class + + Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "MtrrLibUnitTest.h" + +MTRR_MEMORY_CACHE_TYPE mMemoryCacheTypes[] =3D { + CacheUncacheable, CacheWriteCombining, CacheWriteThrough, CacheWriteProt= ected, CacheWriteBack + }; + +UINT64 mFixedMtrrsValue[MTRR_NUMBER_OF_FIXED_MTR= R]; +MSR_IA32_MTRR_PHYSBASE_REGISTER mVariableMtrrsPhysBase[MTRR_NUMBER_OF_VAR= IABLE_MTRR]; +MSR_IA32_MTRR_PHYSMASK_REGISTER mVariableMtrrsPhysMask[MTRR_NUMBER_OF_VAR= IABLE_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; + +/** + Retrieves CPUID information. + + Executes the CPUID instruction with EAX set to the value specified by In= dex. + 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 CP= UID + instruction. + @param Eax The pointer to the 32-bit EAX value returned by the CPUID + instruction. This is an optional parameter that may be NUL= L. + @param Ebx The pointer to the 32-bit EBX value returned by the CPUID + instruction. This is an optional parameter that may be NUL= L. + @param Ecx The pointer to the 32-bit ECX value returned by the CPUID + instruction. This is an optional parameter that may be NUL= L. + @param Edx The pointer to the 32-bit EDX value returned by the CPUID + instruction. This is an optional parameter that may be NUL= L. + + @return Index. + +**/ +UINT32 +EFIAPI +UnitTestMtrrLibAsmCpuid ( + IN UINT32 Index, + OUT UINT32 *Eax, OPTIONAL + OUT UINT32 *Ebx, OPTIONAL + OUT UINT32 *Ecx, OPTIONAL + OUT UINT32 *Edx OPTIONAL + ) +{ + switch (Index) { + case CPUID_VERSION_INFO: + if (Edx !=3D NULL) { + *Edx =3D mCpuidVersionInfoEdx.Uint32; + } + return Index; + break; + case CPUID_EXTENDED_FUNCTION: + if (Eax !=3D NULL) { + *Eax =3D CPUID_VIR_PHY_ADDRESS_SIZE; + } + return Index; + break; + case CPUID_VIR_PHY_ADDRESS_SIZE: + if (Eax !=3D NULL) { + *Eax =3D mCpuidVirPhyAddressSizeEax.Uint32; + } + return Index; + break; + } + + // + // Should never fall through to here + // + ASSERT(FALSE); + return Index; +} + +/** + Returns a 64-bit Machine Specific Register(MSR). + + Reads and returns the 64-bit MSR specified by Index. No parameter checki= ng is + performed on Index, and some Index values may cause CPU exceptions. The + caller must either guarantee that Index is valid, or the caller must set= up + exception handlers to catch the exceptions. This function is only availa= ble + on IA-32 and x64. + + @param MsrIndex The 32-bit MSR index to read. + + @return The value of the MSR identified by MsrIndex. + +**/ +UINT64 +EFIAPI +UnitTestMtrrLibAsmReadMsr64( + IN UINT32 MsrIndex + ) +{ + UINT32 Index; + + for (Index =3D 0; Index < ARRAY_SIZE (mFixedMtrrsValue); Index++) { + if (MsrIndex =3D=3D mFixedMtrrsIndex[Index]) { + return mFixedMtrrsValue[Index]; + } + } + + if ((MsrIndex >=3D MSR_IA32_MTRR_PHYSBASE0) && + (MsrIndex <=3D MSR_IA32_MTRR_PHYSMASK0 + (MTRR_NUMBER_OF_VARIABLE_MT= RR << 1))) { + if (MsrIndex % 2 =3D=3D 0) { + Index =3D (MsrIndex - MSR_IA32_MTRR_PHYSBASE0) >> 1; + return mVariableMtrrsPhysBase[Index].Uint64; + } else { + Index =3D (MsrIndex - MSR_IA32_MTRR_PHYSMASK0) >> 1; + return mVariableMtrrsPhysMask[Index].Uint64; + } + } + + if (MsrIndex =3D=3D MSR_IA32_MTRR_DEF_TYPE) { + return mDefTypeMsr.Uint64; + } + + if (MsrIndex =3D=3D MSR_IA32_MTRRCAP) { + return mMtrrCapMsr.Uint64; + } + + // + // Should never fall through to here + // + ASSERT(FALSE); + return 0; +} + +/** + Writes a 64-bit value to a Machine Specific Register(MSR), and returns t= he + value. + + Writes the 64-bit value specified by Value to the MSR specified by Index= . The + 64-bit value written to the MSR is returned. No parameter checking is + performed on Index or Value, and some of these may cause CPU exceptions.= The + caller must either guarantee that Index and Value are valid, or the call= er + must establish proper exception handlers. This function is only availabl= e on + IA-32 and x64. + + @param MsrIndex The 32-bit MSR index to write. + @param Value The 64-bit value to write to the MSR. + + @return Value + +**/ +UINT64 +EFIAPI +UnitTestMtrrLibAsmWriteMsr64( + IN UINT32 MsrIndex, + IN UINT64 Value + ) +{ + UINT32 Index; + + for (Index =3D 0; Index < ARRAY_SIZE (mFixedMtrrsValue); Index++) { + if (MsrIndex =3D=3D mFixedMtrrsIndex[Index]) { + mFixedMtrrsValue[Index] =3D Value; + return Value; + } + } + + if ((MsrIndex >=3D MSR_IA32_MTRR_PHYSBASE0) && + (MsrIndex <=3D MSR_IA32_MTRR_PHYSMASK0 + (MTRR_NUMBER_OF_VARIABLE_MT= RR << 1))) { + if (MsrIndex % 2 =3D=3D 0) { + Index =3D (MsrIndex - MSR_IA32_MTRR_PHYSBASE0) >> 1; + mVariableMtrrsPhysBase[Index].Uint64 =3D Value; + return Value; + } else { + Index =3D (MsrIndex - MSR_IA32_MTRR_PHYSMASK0) >> 1; + mVariableMtrrsPhysMask[Index].Uint64 =3D Value; + return Value; + } + } + + if (MsrIndex =3D=3D MSR_IA32_MTRR_DEF_TYPE) { + mDefTypeMsr.Uint64 =3D Value; + return Value; + } + + if (MsrIndex =3D=3D MSR_IA32_MTRRCAP) { + mMtrrCapMsr.Uint64 =3D Value; + return Value; + } + + // + // Should never fall through to here + // + ASSERT(FALSE); + return 0; +} + +/** + Initialize MTRR registers. +**/ + +/** + Initialize the MTRR registers. + + @param SystemParameter System parameter that controls the MTRR registers= initialization. +**/ +UNIT_TEST_STATUS +EFIAPI +InitializeMtrrRegs ( + IN MTRR_LIB_SYSTEM_PARAMETER *SystemParameter + ) +{ + UINT32 Index; + + SetMem (mFixedMtrrsValue, sizeof (mFixedMtrrsValue), SystemParameter->De= faultCacheType); + + for (Index =3D 0; Index < ARRAY_SIZE (mVariableMtrrsPhysBase); Index++) { + mVariableMtrrsPhysBase[Index].Uint64 =3D 0; + mVariableMtrrsPhysBase[Index].Bits.Type =3D SystemParameter->Defa= ultCacheType; + mVariableMtrrsPhysBase[Index].Bits.Reserved1 =3D 0; + + mVariableMtrrsPhysMask[Index].Uint64 =3D 0; + mVariableMtrrsPhysMask[Index].Bits.V =3D 0; + mVariableMtrrsPhysMask[Index].Bits.Reserved1 =3D 0; + } + + mDefTypeMsr.Bits.E =3D 1; + mDefTypeMsr.Bits.FE =3D 1; + mDefTypeMsr.Bits.Type =3D SystemParameter->DefaultCacheType; + mDefTypeMsr.Bits.Reserved1 =3D 0; + mDefTypeMsr.Bits.Reserved2 =3D 0; + mDefTypeMsr.Bits.Reserved3 =3D 0; + + mMtrrCapMsr.Bits.SMRR =3D 0; + mMtrrCapMsr.Bits.WC =3D 0; + mMtrrCapMsr.Bits.VCNT =3D SystemParameter->VariableMtrrCount; + mMtrrCapMsr.Bits.FIX =3D SystemParameter->FixedMtrrSupported; + mMtrrCapMsr.Bits.Reserved1 =3D 0; + mMtrrCapMsr.Bits.Reserved2 =3D 0; + mMtrrCapMsr.Bits.Reserved3 =3D 0; + + mCpuidVersionInfoEdx.Bits.MTRR =3D SystemParameter-= >MtrrSupported; + mCpuidVirPhyAddressSizeEax.Bits.PhysicalAddressBits =3D SystemParameter-= >PhysicalAddressBits; + + // + // Hook BaseLib functions used by MtrrLib that require some emulation. + // + gUnitTestHostBaseLib.X86->AsmCpuid =3D UnitTestMtrrLibAsmCpuid; + gUnitTestHostBaseLib.X86->AsmReadMsr64 =3D UnitTestMtrrLibAsmReadMsr64; + gUnitTestHostBaseLib.X86->AsmWriteMsr64 =3D UnitTestMtrrLibAsmWriteMsr64; + + return UNIT_TEST_PASSED; +} + +/** + Collect the test result. + + @param DefaultType Default memory type. + @param PhysicalAddressBits Physical address bits. + @param VariableMtrrCount Count of variable MTRRs. + @param Mtrrs MTRR settings to collect from. + @param Ranges Return the memory ranges. + @param RangeCount Return the count of memory ranges. + @param MtrrCount Return the count of variable MTRRs being use= d. +**/ +VOID +CollectTestResult ( + IN MTRR_MEMORY_CACHE_TYPE DefaultType, + IN UINT32 PhysicalAddressBits, + IN UINT32 VariableMtrrCount, + IN MTRR_SETTINGS *Mtrrs, + OUT MTRR_MEMORY_RANGE *Ranges, + IN OUT UINTN *RangeCount, + OUT UINT32 *MtrrCount + ) +{ + UINTN Index; + UINT64 MtrrValidBitsMask; + UINT64 MtrrValidAddressMask; + MTRR_MEMORY_RANGE RawMemoryRanges[ARRAY_SIZE (Mtrrs->Variables.Mtrr)]; + + ASSERT (Mtrrs !=3D NULL); + ASSERT (VariableMtrrCount <=3D ARRAY_SIZE (Mtrrs->Variables.Mtrr)); + + MtrrValidBitsMask =3D (1ull << PhysicalAddressBits) - 1; + MtrrValidAddressMask =3D MtrrValidBitsMask & ~0xFFFull; + + *MtrrCount =3D 0; + for (Index =3D 0; Index < VariableMtrrCount; Index++) { + if (((MSR_IA32_MTRR_PHYSMASK_REGISTER *) &Mtrrs->Variables.Mtrr[Index]= .Mask)->Bits.V =3D=3D 1) { + RawMemoryRanges[*MtrrCount].BaseAddress =3D Mtrrs->Variables.Mtrr[In= dex].Base & MtrrValidAddressMask; + RawMemoryRanges[*MtrrCount].Type =3D + ((MSR_IA32_MTRR_PHYSBASE_REGISTER *) &Mtrrs->Variables.Mtrr[Index]= .Base)->Bits.Type; + RawMemoryRanges[*MtrrCount].Length =3D + ((~(Mtrrs->Variables.Mtrr[Index].Mask & MtrrValidAddressMask)) &= MtrrValidBitsMask) + 1; + (*MtrrCount)++; + } + } + + GetEffectiveMemoryRanges (DefaultType, PhysicalAddressBits, RawMemoryRan= ges, *MtrrCount, Ranges, RangeCount); +} + +/** + Return a 32bit random number. + + @param Start Start of the random number range. + @param Limit Limit of the random number range. + @return 32bit random number +**/ +UINT32 +Random32 ( + UINT32 Start, + UINT32 Limit + ) +{ + return (UINT32) (((double) rand () / RAND_MAX) * (Limit - Start)) + Star= t; +} + +/** + Return a 64bit random number. + + @param Start Start of the random number range. + @param Limit Limit of the random number range. + @return 64bit random number +**/ +UINT64 +Random64 ( + UINT64 Start, + UINT64 Limit + ) +{ + return (UINT64) (((double) rand () / RAND_MAX) * (Limit - Start)) + Star= t; +} + +/** + Generate random MTRR BASE/MASK for a specified type. + + @param PhysicalAddressBits Physical address bits. + @param CacheType Cache type. + @param MtrrPair Return the random MTRR. + @param MtrrMemoryRange Return the random memory range. +**/ +VOID +GenerateRandomMtrrPair ( + IN UINT32 PhysicalAddressBits, + IN MTRR_MEMORY_CACHE_TYPE CacheType, + OUT MTRR_VARIABLE_SETTING *MtrrPair, OPTIONAL + OUT MTRR_MEMORY_RANGE *MtrrMemoryRange OPTIONAL + ) +{ + MSR_IA32_MTRR_PHYSBASE_REGISTER PhysBase; + MSR_IA32_MTRR_PHYSMASK_REGISTER PhysMask; + UINT32 SizeShift; + UINT32 BaseShift; + UINT64 RandomBoundary; + UINT64 MaxPhysicalAddress; + UINT64 RangeSize; + UINT64 RangeBase; + UINT64 PhysBasePhyMaskValidBitsMask; + + MaxPhysicalAddress =3D 1ull << PhysicalAddressBits; + do { + SizeShift =3D Random32 (12, PhysicalAddressBits - 1); + RangeSize =3D 1ull << SizeShift; + + BaseShift =3D Random32 (SizeShift, PhysicalAddressBits - 1); + RandomBoundary =3D Random64 (0, 1ull << (PhysicalAddressBits - BaseShi= ft)); + RangeBase =3D RandomBoundary << BaseShift; + } while (RangeBase < SIZE_1MB || RangeBase > MaxPhysicalAddress - 1); + + PhysBasePhyMaskValidBitsMask =3D (MaxPhysicalAddress - 1) & 0xffffffffff= fff000ULL; + + PhysBase.Uint64 =3D 0; + PhysBase.Bits.Type =3D CacheType; + PhysBase.Uint64 |=3D RangeBase & PhysBasePhyMaskValidBitsMask; + PhysMask.Uint64 =3D 0; + PhysMask.Bits.V =3D 1; + PhysMask.Uint64 |=3D ((~RangeSize) + 1) & PhysBasePhyMaskValidBitsMask; + + if (MtrrPair !=3D NULL) { + MtrrPair->Base =3D PhysBase.Uint64; + MtrrPair->Mask =3D PhysMask.Uint64; + } + + if (MtrrMemoryRange !=3D NULL) { + MtrrMemoryRange->BaseAddress =3D RangeBase; + MtrrMemoryRange->Length =3D RangeSize; + MtrrMemoryRange->Type =3D CacheType; + } +} + + +/** + Check whether the Range overlaps with any one in Ranges. + + @param Range The memory range to check. + @param Ranges The memory ranges. + @param Count Count of memory ranges. + + @return TRUE when overlap exists. +**/ +BOOLEAN +RangesOverlap ( + IN MTRR_MEMORY_RANGE *Range, + IN MTRR_MEMORY_RANGE *Ranges, + IN UINTN Count + ) +{ + while (Count-- !=3D 0) { + // + // Two ranges overlap when: + // 1. range#2.base is in the middle of range#1 + // 2. range#1.base is in the middle of range#2 + // + if ((Range->BaseAddress <=3D Ranges[Count].BaseAddress && Ranges[Count= ].BaseAddress < Range->BaseAddress + Range->Length) + || (Ranges[Count].BaseAddress <=3D Range->BaseAddress && Range->BaseA= ddress < Ranges[Count].BaseAddress + Ranges[Count].Length)) { + return TRUE; + } + } + return FALSE; +} + +/** + Generate random MTRRs. + + @param PhysicalAddressBits Physical address bits. + @param RawMemoryRanges Return the randomly generated MTRRs. + @param UcCount Count of Uncacheable MTRRs. + @param WtCount Count of Write Through MTRRs. + @param WbCount Count of Write Back MTRRs. + @param WpCount Count of Write Protected MTRRs. + @param WcCount Count of Write Combine MTRRs. +**/ +VOID +GenerateValidAndConfigurableMtrrPairs ( + IN UINT32 PhysicalAddressBits, + IN OUT MTRR_MEMORY_RANGE *RawMemoryRanges, + IN UINT32 UcCount, + IN UINT32 WtCount, + IN UINT32 WbCount, + IN UINT32 WpCount, + IN UINT32 WcCount + ) +{ + UINT32 Index; + + // + // 1. Generate UC, WT, WB in order. + // + for (Index =3D 0; Index < UcCount; Index++) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheUncacheable, NULL, &= RawMemoryRanges[Index]); + } + + for (Index =3D UcCount; Index < UcCount + WtCount; Index++) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteThrough, NULL, = &RawMemoryRanges[Index]); + } + + for (Index =3D UcCount + WtCount; Index < UcCount + WtCount + WbCount; I= ndex++) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteBack, NULL, &Ra= wMemoryRanges[Index]); + } + + // + // 2. Generate WP MTRR and DO NOT overlap with WT, WB. + // + for (Index =3D UcCount + WtCount + WbCount; Index < UcCount + WtCount + = WbCount + WpCount; Index++) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteProtected, NULL= , &RawMemoryRanges[Index]); + while (RangesOverlap (&RawMemoryRanges[Index], &RawMemoryRanges[UcCoun= t], WtCount + WbCount)) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteProtected, NU= LL, &RawMemoryRanges[Index]); + } + } + + // + // 3. Generate WC MTRR and DO NOT overlap with WT, WB, WP. + // + for (Index =3D UcCount + WtCount + WbCount + WpCount; Index < UcCount + = WtCount + WbCount + WpCount + WcCount; Index++) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteCombining, NULL= , &RawMemoryRanges[Index]); + while (RangesOverlap (&RawMemoryRanges[Index], &RawMemoryRanges[UcCoun= t], WtCount + WbCount + WpCount)) { + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteCombining, NU= LL, &RawMemoryRanges[Index]); + } + } +} + +/** + Return a random memory cache type. +**/ +MTRR_MEMORY_CACHE_TYPE +GenerateRandomCacheType ( + VOID + ) +{ + return mMemoryCacheTypes[Random32 (0, ARRAY_SIZE (mMemoryCacheTypes) -= 1)]; +} + +/** + Compare function used by qsort(). +**/ + +/** + Compare function used by qsort(). + + @param Left Left operand to compare. + @param Right Right operand to compare. + + @retval 0 Left =3D=3D Right + @retval -1 Left < Right + @retval 1 Left > Right +**/ +INT32 +CompareFuncUint64 ( + CONST VOID * Left, + CONST VOID * Right + ) +{ + INT64 Delta; + Delta =3D (*(UINT64*)Left - *(UINT64*)Right); + if (Delta > 0) { + return 1; + } else if (Delta =3D=3D 0) { + return 0; + } else { + return -1; + } +} + +/** + Determin the memory cache type for the Range. + + @param DefaultType Default cache type. + @param Range The memory range to determin the cache type. + @param Ranges The entire memory ranges. + @param RangeCount Count of the entire memory ranges. +**/ +VOID +DetermineMemoryCacheType ( + IN MTRR_MEMORY_CACHE_TYPE DefaultType, + IN OUT MTRR_MEMORY_RANGE *Range, + IN MTRR_MEMORY_RANGE *Ranges, + IN UINT32 RangeCount + ) +{ + UINT32 Index; + Range->Type =3D CacheInvalid; + for (Index =3D 0; Index < RangeCount; Index++) { + if (RangesOverlap (Range, &Ranges[Index], 1)) { + if (Ranges[Index].Type < Range->Type) { + Range->Type =3D Ranges[Index].Type; + } + } + } + + if (Range->Type =3D=3D CacheInvalid) { + Range->Type =3D DefaultType; + } +} + +/** + Get the index of the element that does NOT equals to Array[Index]. + + @param Index Current element. + @param Array Array to scan. + @param Count Count of the array. + + @return Next element that doesn't equal to current one. +**/ +UINT32 +GetNextDifferentElementInSortedArray ( + IN UINT32 Index, + IN UINT64 *Array, + IN UINT32 Count + ) +{ + UINT64 CurrentElement; + CurrentElement =3D Array[Index]; + while (CurrentElement =3D=3D Array[Index] && Index < Count) { + Index++; + } + return Index; +} + +/** + Remove the duplicates from the array. + + @param Array The array to operate on. + @param Count Count of the array. +**/ +VOID +RemoveDuplicatesInSortedArray ( + IN OUT UINT64 *Array, + IN OUT UINT32 *Count + ) +{ + UINT32 Index; + UINT32 NewCount; + + Index =3D 0; + NewCount =3D 0; + while (Index < *Count) { + Array[NewCount] =3D Array[Index]; + NewCount++; + Index =3D GetNextDifferentElementInSortedArray (Index, Array, *Count); + } + *Count =3D NewCount; +} + +/** + Return TRUE when Address is in the Range. + + @param Address The address to check. + @param Range The range to check. + @return TRUE when Address is in the Range. +**/ +BOOLEAN +AddressInRange ( + IN UINT64 Address, + IN MTRR_MEMORY_RANGE Range + ) +{ + return (Address >=3D Range.BaseAddress) && (Address <=3D Range.BaseAdd= ress + Range.Length - 1); +} + +/** + Get the overlap bit flag. + + @param RawMemoryRanges Raw memory ranges. + @param RawMemoryRangeCount Count of raw memory ranges. + @param Address The address to check. +**/ +UINT64 +GetOverlapBitFlag ( + IN MTRR_MEMORY_RANGE *RawMemoryRanges, + IN UINT32 RawMemoryRangeCount, + IN UINT64 Address + ) +{ + UINT64 OverlapBitFlag; + UINT32 Index; + OverlapBitFlag =3D 0; + for (Index =3D 0; Index < RawMemoryRangeCount; Index++) { + if (AddressInRange (Address, RawMemoryRanges[Index])) { + OverlapBitFlag |=3D (1ull << Index); + } + } + + return OverlapBitFlag; +} + +/** + Return the relationship between flags. + + @param Flag1 Flag 1 + @param Flag2 Flag 2 + + @retval 0 Flag1 =3D=3D Flag2 + @retval 1 Flag1 is a subset of Flag2 + @retval 2 Flag2 is a subset of Flag1 + @retval 3 No subset relations between Flag1 and Flag2. +**/ +UINT32 +CheckOverlapBitFlagsRelation ( + IN UINT64 Flag1, + IN UINT64 Flag2 + ) +{ + if (Flag1 =3D=3D Flag2) return 0; + if ((Flag1 | Flag2) =3D=3D Flag2) return 1; + if ((Flag1 | Flag2) =3D=3D Flag1) return 2; + return 3; +} + +/** + Return TRUE when the Endpoint is in any of the Ranges. + + @param Endpoint The endpoint to check. + @param Ranges The memory ranges. + @param RangeCount Count of memory ranges. + + @retval TRUE Endpoint is in one of the range. + @retval FALSE Endpoint is not in any of the ranges. +**/ +BOOLEAN +IsEndpointInRanges ( + IN UINT64 Endpoint, + IN MTRR_MEMORY_RANGE *Ranges, + IN UINTN RangeCount + ) +{ + UINT32 Index; + for (Index =3D 0; Index < RangeCount; Index++) { + if (AddressInRange (Endpoint, Ranges[Index])) { + return TRUE; + } + } + return FALSE; +} + + +/** + Compact adjacent ranges of the same type. + + @param DefaultType Default memory type. + @param PhysicalAddressBits Physical address bits. + @param EffectiveMtrrMemoryRanges Memory ranges to compact. + @param EffectiveMtrrMemoryRangesCount Return the new count of memory ran= ges. +**/ +VOID +CompactAndExtendEffectiveMtrrMemoryRanges ( + IN MTRR_MEMORY_CACHE_TYPE DefaultType, + IN UINT32 PhysicalAddressBits, + IN OUT MTRR_MEMORY_RANGE **EffectiveMtrrMemoryRanges, + IN OUT UINTN *EffectiveMtrrMemoryRangesCount + ) +{ + UINT64 MaxAddress; + UINTN NewRangesCountAtMost; + MTRR_MEMORY_RANGE *NewRanges; + UINTN NewRangesCountActual; + MTRR_MEMORY_RANGE *CurrentRangeInNewRanges; + MTRR_MEMORY_CACHE_TYPE CurrentRangeTypeInOldRanges; + + MTRR_MEMORY_RANGE *OldRanges; + MTRR_MEMORY_RANGE OldLastRange; + UINTN OldRangesIndex; + + NewRangesCountActual =3D 0; + NewRangesCountAtMost =3D *EffectiveMtrrMemoryRangesCount + 2; // At mo= st with 2 more range entries. + NewRanges =3D (MTRR_MEMORY_RANGE *) calloc (NewRangesCountAtM= ost, sizeof (MTRR_MEMORY_RANGE)); + OldRanges =3D *EffectiveMtrrMemoryRanges; + if (OldRanges[0].BaseAddress > 0) { + NewRanges[NewRangesCountActual].BaseAddress =3D 0; + NewRanges[NewRangesCountActual].Length =3D OldRanges[0].BaseAddre= ss; + NewRanges[NewRangesCountActual].Type =3D DefaultType; + NewRangesCountActual++; + } + + OldRangesIndex =3D 0; + while (OldRangesIndex < *EffectiveMtrrMemoryRangesCount) { + CurrentRangeTypeInOldRanges =3D OldRanges[OldRangesIndex].Type; + CurrentRangeInNewRanges =3D NULL; + if (NewRangesCountActual > 0) // We need to check CurrentNewRange fi= rst before generate a new NewRange. + { + CurrentRangeInNewRanges =3D &NewRanges[NewRangesCountActual - 1]; + } + if (CurrentRangeInNewRanges !=3D NULL && CurrentRangeInNewRanges->Type= =3D=3D CurrentRangeTypeInOldRanges) { + CurrentRangeInNewRanges->Length +=3D OldRanges[OldRangesIndex].Lengt= h; + } else { + NewRanges[NewRangesCountActual].BaseAddress =3D OldRanges[OldRangesI= ndex].BaseAddress; + NewRanges[NewRangesCountActual].Length +=3D OldRanges[OldRangesI= ndex].Length; + NewRanges[NewRangesCountActual].Type =3D CurrentRangeTypeInOl= dRanges; + while (OldRangesIndex + 1 < *EffectiveMtrrMemoryRangesCount && OldRa= nges[OldRangesIndex + 1].Type =3D=3D CurrentRangeTypeInOldRanges) + { + OldRangesIndex++; + NewRanges[NewRangesCountActual].Length +=3D OldRanges[OldRangesInd= ex].Length; + } + NewRangesCountActual++; + } + + OldRangesIndex++; + } + + MaxAddress =3D (1ull << PhysicalAddressBits) - 1; + OldLastRange =3D OldRanges[(*EffectiveMtrrMemoryRangesCount) - 1]; + CurrentRangeInNewRanges =3D &NewRanges[NewRangesCountActual - 1]; + if (OldLastRange.BaseAddress + OldLastRange.Length - 1 < MaxAddress) { + if (CurrentRangeInNewRanges->Type =3D=3D DefaultType) { + CurrentRangeInNewRanges->Length =3D MaxAddress - CurrentRangeInNewRa= nges->BaseAddress + 1; + } else { + NewRanges[NewRangesCountActual].BaseAddress =3D OldLastRange.BaseAdd= ress + OldLastRange.Length; + NewRanges[NewRangesCountActual].Length =3D MaxAddress - NewRanges[Ne= wRangesCountActual].BaseAddress + 1; + NewRanges[NewRangesCountActual].Type =3D DefaultType; + NewRangesCountActual++; + } + } + + free (*EffectiveMtrrMemoryRanges); + *EffectiveMtrrMemoryRanges =3D NewRanges; + *EffectiveMtrrMemoryRangesCount =3D NewRangesCountActual; +} + +/** + Collect all the endpoints in the raw memory ranges. + + @param Endpoints Return the collected endpoints. + @param EndPointCount Return the count of endpoints. + @param RawMemoryRanges Raw memory ranges. + @param RawMemoryRangeCount Count of raw memory ranges. +**/ +VOID +CollectEndpoints ( + IN OUT UINT64 *Endpoints, + IN OUT UINT32 *EndPointCount, + IN MTRR_MEMORY_RANGE *RawMemoryRanges, + IN UINT32 RawMemoryRangeCount + ) +{ + UINT32 Index; + UINT32 RawRangeIndex; + + ASSERT ((RawMemoryRangeCount << 1) =3D=3D *EndPointCount); + + for (Index =3D 0; Index < *EndPointCount; Index +=3D 2) { + RawRangeIndex =3D Index >> 1; + Endpoints[Index] =3D RawMemoryRanges[RawRangeIndex].BaseAddress; + Endpoints[Index + 1] =3D RawMemoryRanges[RawRangeIndex].BaseAddress + = RawMemoryRanges[RawRangeIndex].Length - 1; + } + + qsort (Endpoints, *EndPointCount, sizeof (UINT64), CompareFuncUint64); + RemoveDuplicatesInSortedArray (Endpoints, EndPointCount); +} + +/** + Convert the MTRR BASE/MASK array to memory ranges. + + @param DefaultType Default memory type. + @param PhysicalAddressBits Physical address bits. + @param RawMemoryRanges Raw memory ranges. + @param RawMemoryRangeCount Count of raw memory ranges. + @param MemoryRanges Memory ranges. + @param MemoryRangeCount Count of memory ranges. +**/ +VOID +GetEffectiveMemoryRanges ( + IN MTRR_MEMORY_CACHE_TYPE DefaultType, + IN UINT32 PhysicalAddressBits, + IN MTRR_MEMORY_RANGE *RawMemoryRanges, + IN UINT32 RawMemoryRangeCount, + OUT MTRR_MEMORY_RANGE *MemoryRanges, + OUT UINTN *MemoryRangeCount + ) +{ + UINTN Index; + UINT32 AllEndPointsCount; + UINT64 *AllEndPointsInclusive; + UINT32 AllRangePiecesCountMax; + MTRR_MEMORY_RANGE *AllRangePieces; + UINTN AllRangePiecesCountActual; + UINT64 OverlapBitFlag1; + UINT64 OverlapBitFlag2; + INT32 OverlapFlagRelation; + + if (RawMemoryRangeCount =3D=3D 0) { + MemoryRanges[0].BaseAddress =3D 0; + MemoryRanges[0].Length =3D (1ull << PhysicalAddressBits); + MemoryRanges[0].Type =3D DefaultType; + *MemoryRangeCount =3D 1; + return; + } + + AllEndPointsCount =3D RawMemoryRangeCount << 1; + AllEndPointsInclusive =3D calloc (AllEndPointsCount, sizeof (UINT64)= ); + AllRangePiecesCountMax =3D RawMemoryRangeCount * 3 + 1; + AllRangePieces =3D calloc (AllRangePiecesCountMax, sizeof (MT= RR_MEMORY_RANGE)); + CollectEndpoints (AllEndPointsInclusive, &AllEndPointsCount, RawMemoryRa= nges, RawMemoryRangeCount); + + for (Index =3D 0, AllRangePiecesCountActual =3D 0; Index < AllEndPointsC= ount - 1; Index++) { + OverlapBitFlag1 =3D GetOverlapBitFlag (RawMemoryRanges, RawMemoryRange= Count, AllEndPointsInclusive[Index]); + OverlapBitFlag2 =3D GetOverlapBitFlag (RawMemoryRanges, RawMemoryRange= Count, AllEndPointsInclusive[Index + 1]); + OverlapFlagRelation =3D CheckOverlapBitFlagsRelation (OverlapBitFlag1,= OverlapBitFlag2); + switch (OverlapFlagRelation) { + case 0: // [1, 2] + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEndPo= intsInclusive[Index]; + AllRangePieces[AllRangePiecesCountActual].Length =3D AllEndPo= intsInclusive[Index + 1] - AllEndPointsInclusive[Index] + 1; + AllRangePiecesCountActual++; + break; + case 1: // [1, 2) + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEndPo= intsInclusive[Index]; + AllRangePieces[AllRangePiecesCountActual].Length =3D (AllEndP= ointsInclusive[Index + 1] - 1) - AllEndPointsInclusive[Index] + 1; + AllRangePiecesCountActual++; + break; + case 2: // (1, 2] + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEndPo= intsInclusive[Index] + 1; + AllRangePieces[AllRangePiecesCountActual].Length =3D AllEndPo= intsInclusive[Index + 1] - (AllEndPointsInclusive[Index] + 1) + 1; + AllRangePiecesCountActual++; + + if (!IsEndpointInRanges (AllEndPointsInclusive[Index], AllRangePie= ces, AllRangePiecesCountActual)) { + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEnd= PointsInclusive[Index]; + AllRangePieces[AllRangePiecesCountActual].Length =3D 1; + AllRangePiecesCountActual++; + } + break; + case 3: // (1, 2) + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEndPo= intsInclusive[Index] + 1; + AllRangePieces[AllRangePiecesCountActual].Length =3D (AllEndP= ointsInclusive[Index + 1] - 1) - (AllEndPointsInclusive[Index] + 1) + 1; + if (AllRangePieces[AllRangePiecesCountActual].Length =3D=3D 0) /= / Only in case 3 can exists Length=3D0, we should skip such "segment". + break; + AllRangePiecesCountActual++; + if (!IsEndpointInRanges (AllEndPointsInclusive[Index], AllRangePie= ces, AllRangePiecesCountActual)) { + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEnd= PointsInclusive[Index]; + AllRangePieces[AllRangePiecesCountActual].Length =3D 1; + AllRangePiecesCountActual++; + } + break; + default: + ASSERT (FALSE); + } + } + + for (Index =3D 0; Index < AllRangePiecesCountActual; Index++) { + DetermineMemoryCacheType (DefaultType, &AllRangePieces[Index], RawMemo= ryRanges, RawMemoryRangeCount); + } + + CompactAndExtendEffectiveMtrrMemoryRanges (DefaultType, PhysicalAddressB= its, &AllRangePieces, &AllRangePiecesCountActual); + ASSERT (*MemoryRangeCount >=3D AllRangePiecesCountActual); + memcpy (MemoryRanges, AllRangePieces, AllRangePiecesCountActual * sizeof= (MTRR_MEMORY_RANGE)); + *MemoryRangeCount =3D AllRangePiecesCountActual; + + free (AllEndPointsInclusive); + free (AllRangePieces); +} diff --git a/UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc b/UefiCpuPkg/Test/UefiC= puPkgHostTest.dsc new file mode 100644 index 0000000000..8a5c456830 --- /dev/null +++ b/UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc @@ -0,0 +1,31 @@ +## @file +# UefiCpuPkg DSC file used to build host-based unit tests. +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME =3D UefiCpuPkgHostTest + PLATFORM_GUID =3D E00B9599-5B74-4FF7-AB9F-8183FB13B2F9 + PLATFORM_VERSION =3D 0.1 + DSC_SPECIFICATION =3D 0x00010005 + OUTPUT_DIRECTORY =3D Build/UefiCpuPkg/HostTest + SUPPORTED_ARCHITECTURES =3D IA32|X64 + BUILD_TARGETS =3D NOOPT + SKUID_IDENTIFIER =3D DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[LibraryClasses] + MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf + +[PcdsPatchableInModule] + gUefiCpuPkgTokenSpaceGuid.PcdCpuNumberOfReservedVariableMtrrs|0 + +[Components] + # + # Build HOST_APPLICATION that tests the MtrrLib + # + UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTestHost.inf diff --git a/UefiCpuPkg/UefiCpuPkg.ci.yaml b/UefiCpuPkg/UefiCpuPkg.ci.yaml index 99e460a8b0..4559b40105 100644 --- a/UefiCpuPkg/UefiCpuPkg.ci.yaml +++ b/UefiCpuPkg/UefiCpuPkg.ci.yaml @@ -8,6 +8,10 @@ "CompilerPlugin": { "DscPath": "UefiCpuPkg.dsc" }, + ## options defined ci/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "Test/UefiCpuPkgHostTest.dsc" + }, "CharEncodingCheck": { "IgnoreFiles": [] }, @@ -18,7 +22,9 @@ "UefiCpuPkg/UefiCpuPkg.dec" ], # For host based unit tests - "AcceptableDependencies-HOST_APPLICATION":[], + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], # For UEFI shell based apps "AcceptableDependencies-UEFI_APPLICATION":[], "IgnoreInf": [] @@ -30,6 +36,10 @@ "UefiCpuPkg/ResetVector/Vtf0/Vtf0.inf" ] }, + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "Test/UefiCpuPkgHostTest.dsc" + }, "GuidCheck": { "IgnoreGuidName": ["SecCore", "ResetVector"], # Expected duplicati= on for gEfiFirmwareVolumeTopFileGuid "IgnoreGuidValue": [], --=20 2.27.0.windows.1 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#63380): https://edk2.groups.io/g/devel/message/63380 Mute This Topic: https://groups.io/mt/75837117/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-