From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from NAM12-DM6-obe.outbound.protection.outlook.com (NAM12-DM6-obe.outbound.protection.outlook.com [40.107.243.102]) by mx.groups.io with SMTP id smtpd.web12.18318.1595958819593505623 for ; Tue, 28 Jul 2020 10:53:39 -0700 Authentication-Results: mx.groups.io; dkim=pass header.i=@microsoft.com header.s=selector2 header.b=X66JHpVD; spf=pass (domain: microsoft.com, ip: 40.107.243.102, mailfrom: bret.barkelew@microsoft.com) ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=hIBu/9tZmKbkBHOA+LCWJ5V55AG5FtMfS/3Ou8unJDcQGxzaWnnL2XDwQUAp+wYVMjeqA8J8rXpH7KoRPyn0LoxBtWGhWw++3fVA3JVC8vd81IBByFxHAREvjw/RslMbSBXNYSDCDVlUmbD8GhGN4wBZBXicp2js9jDd6tOj1wcQIAttD5XDlrNH/SycbM5Oej3DeRlGOyJ5EbkOFcgTXb1W04FO76rahO2gEabWjFyCm6d5yiVkPLc8TiGLZeQO0QBM7SE/+kX2+dVWfZXdBirtq9u6lX5uoFj3OVyS33caeoR/Lui7zCw4paWX3B6SYO8h6t36xh+zyMJPH/3e/Q== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector9901; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=ZM3pZamvhLKB4pAFv0iYX291oeTGyaNcs+punkLe7mo=; b=iFFsxirOz7YRgVp58YZw1NRqY04nEO7f2w5GvYMv+8g9o4vESOyAAKMgtqztmf1CoLVh0tNRpZPKnb77prqQhKwS/4towRw9KLdj23cic8jPYlgEcjeW84IjQTOOSGe5+v42Dh5biqqfLwNsVhMQgAl+zECkpcZPKfLcC6/ctLKvXiZ+jEaeVh1Em0w+ubDI5cgLU46EC6mWM0C5oz5FEbDdi0np5I/Hy/o3BwHXcz95jnMAoHkmL5R537dJF/52bbTwzWwhloMIYXZ/IOh5uJOdGHmRjQU1/AtPpsdg9HgjeE4FA7l4mNWzc8cJUaDuuMLhFJWxgOT3NSuKzWPbpw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=microsoft.com; dmarc=pass action=none header.from=microsoft.com; dkim=pass header.d=microsoft.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=ZM3pZamvhLKB4pAFv0iYX291oeTGyaNcs+punkLe7mo=; b=X66JHpVD++k+ntVCeu/s/IVGAGgl84VWd+UTfquTNthBIRHDYGVsrpQzokapwWLG7rwsVhwq+3We4jL8W9ug1kaNdHZEz2WeHMS8qW9pkuCzlbhd0qPiin8BnUzQu5KxsHtCmAUwrztlKxALn6G1fvKPiu8TcNzv+Txv0jBLmYU= Received: from CY4PR21MB0743.namprd21.prod.outlook.com (2603:10b6:903:b2::9) by CY4PR21MB0744.namprd21.prod.outlook.com (2603:10b6:903:b2::10) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3239.7; Tue, 28 Jul 2020 17:53:33 +0000 Received: from CY4PR21MB0743.namprd21.prod.outlook.com ([fe80::2ca0:7d3e:e918:c47a]) by CY4PR21MB0743.namprd21.prod.outlook.com ([fe80::2ca0:7d3e:e918:c47a%12]) with mapi id 15.20.3239.016; Tue, 28 Jul 2020 17:53:33 +0000 From: "Bret Barkelew" To: "tim.lewis@insyde.com" , "devel@edk2.groups.io" , "spbrogan@outlook.com" , "Ni, Ray" CC: "Kinney, Michael D" , 'Ming Shao' , "Dong, Eric" , 'Laszlo Ersek' , Sean Brogan , "Yao, Jiewen" Subject: Re: [EXTERNAL] RE: [edk2-devel] [PATCH v4] UefiCpuPkg/MtrrLib/UnitTest: Add host based unit test Thread-Topic: [EXTERNAL] RE: [edk2-devel] [PATCH v4] UefiCpuPkg/MtrrLib/UnitTest: Add host based unit test Thread-Index: AQHWZP140BmFSq07UEWHb6S3/XYSjqkdOs6AgAAKuOE= Date: Tue, 28 Jul 2020 17:53:33 +0000 Message-ID: References: ,<04ae01d66502$67338d20$359aa760$@insyde.com> In-Reply-To: <04ae01d66502$67338d20$359aa760$@insyde.com> Accept-Language: en-US X-MS-Has-Attach: X-MS-TNEF-Correlator: msip_labels: MSIP_Label_f42aa342-8706-4288-bd11-ebb85995028c_Enabled=True;MSIP_Label_f42aa342-8706-4288-bd11-ebb85995028c_SiteId=72f988bf-86f1-41af-91ab-2d7cd011db47;MSIP_Label_f42aa342-8706-4288-bd11-ebb85995028c_SetDate=2020-07-28T17:51:42.1442397Z;MSIP_Label_f42aa342-8706-4288-bd11-ebb85995028c_ContentBits=0;MSIP_Label_f42aa342-8706-4288-bd11-ebb85995028c_Method=Privileged authentication-results: insyde.com; dkim=none (message not signed) header.d=none;insyde.com; dmarc=none action=none header.from=microsoft.com; x-originating-ip: [174.21.66.92] x-ms-publictraffictype: Email x-ms-office365-filtering-ht: Tenant x-ms-office365-filtering-correlation-id: 8b35eec8-8fd9-4a55-188f-08d8331f252e x-ms-traffictypediagnostic: CY4PR21MB0744: x-ms-exchange-transport-forked: True x-ld-processed: 72f988bf-86f1-41af-91ab-2d7cd011db47,ExtAddr x-microsoft-antispam-prvs: x-ms-oob-tlc-oobclassifiers: OLM:10000; x-ms-exchange-senderadcheck: 1 x-microsoft-antispam: BCL:0; x-microsoft-antispam-message-info: 17GUl4AVONttpFimPj9qxoJUUiiGCIOAa6iHTl/eMQI/6V1omlKBM7om8o8eGNjfxcTqDqviFC5FvvbYCbT6sx4YHyLDUXrx4EhEkLvJtmPGKSUNlnOxJfikiC3I6HcHccocrgPhDZHufmgu8PSKh0G2QFKiP0yF1RuDrHcCDS3SmqR65014Q1/alGTpr/GM5eYdiWTCPejUn1t2eqv4OugvuLgEt5UhPt9mWKgBUQk5OQq7Kol2psel9XUhfrUFCZgA0D1R6JfWC7SIoTSmZ2vKptiyA+JVG9ZVRZKTvIH0ah5rIbplC0PVIICemIQl/dp5ivtm/NOpgXaQQ31iyvwtc4uXYETCzHh7g9ouH29fRGoJ1eYfGJfuFy2DyYZ06TmwMdRD6scLLCmIJmzD4w== x-forefront-antispam-report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CY4PR21MB0743.namprd21.prod.outlook.com;PTR:;CAT:NONE;SFTY:;SFS:(4636009)(39860400002)(396003)(346002)(366004)(136003)(376002)(66946007)(66556008)(66476007)(64756008)(66446008)(10290500003)(91956017)(76116006)(33656002)(8990500004)(6506007)(110136005)(82950400001)(26005)(52536014)(82960400001)(54906003)(8936002)(55016002)(53546011)(316002)(186003)(9686003)(5660300002)(8676002)(86362001)(71200400001)(7696005)(166002)(4326008)(2906002)(966005)(478600001)(83380400001)(19627235002)(30864003)(579004)(559001);DIR:OUT;SFP:1102; x-ms-exchange-antispam-messagedata: x5+f/+PCCtrK37NA0N5BX2YleIOQz0lsu0pBSAYvB/2Qa6bki5VwDlRI+hz67lrXi0cFrjxy9laYbY1NXbEW05/8oRuEGXSc/kwXTaoM/dc4SKbJewT6Fy8eKbFV4UsjggksIhjZqy5BBgb25hG5v0l2fVqBG6OzlTBDhKDR30tHW5QupBNAK8QkxXRO39eaMcWJHM/D6lBzah/VVug7tQ53D9hM9t8oP+U/cwYoaIXMNS5HUy2u93IsbhGM8F/kKt2nFInoMLiB8mWXSNbWesD3Ih7ywA+EPf4xXpwUA0Kh6DD3cXpPUUVK43H+TycbISr5rzhUAA2DBUlw3KrxZOtilmi43yk7g/C4FnA18H+htuXavGK0omtiz43yAEX/vV8J4pi5QrhJ0dvNYYUz+Wfb/rR7NowtLoQ4YQjAcl+BWiNSNBZ7mB5Mf93fbnNw5988K4ZgnjibFh5PbJs1yuzkN2ztA9hyTSuyuX1s/2z/+ey2mAjpDxCMeoIqWY9XF5CL30+9x0+9zIKvIT1t734wqSzBYkngGlCu+A+RiEpP7AcuhUQiwBf4vYp28vKPOZfk8ygL3xupYMXRmJX2cbGs1jlwNhN+QN8TUZvkk5hbSC2GZtxDRoy3Lw+X/jglmvlTIZqNzwFfPto0EyJtUA== MIME-Version: 1.0 X-OriginatorOrg: microsoft.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-AuthSource: CY4PR21MB0743.namprd21.prod.outlook.com X-MS-Exchange-CrossTenant-Network-Message-Id: 8b35eec8-8fd9-4a55-188f-08d8331f252e X-MS-Exchange-CrossTenant-originalarrivaltime: 28 Jul 2020 17:53:33.1716 (UTC) X-MS-Exchange-CrossTenant-fromentityheader: Hosted X-MS-Exchange-CrossTenant-id: 72f988bf-86f1-41af-91ab-2d7cd011db47 X-MS-Exchange-CrossTenant-mailboxtype: HOSTED X-MS-Exchange-CrossTenant-userprincipalname: iIq9qNVO8MB3yh/wPqTdFPhTqY1+sxEW9rjZ142ZOqkN9+ftpzGHI7qNJXLpOO48Cqxp4F4eB58l5kqMpg9qpw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: CY4PR21MB0744 Content-Language: en-US Content-Type: multipart/alternative; boundary="_000_CY4PR21MB07430EEAF012BC185B3DC28AEF730CY4PR21MB0743namp_" --_000_CY4PR21MB07430EEAF012BC185B3DC28AEF730CY4PR21MB0743namp_ Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable In this strategy, the seed would function like a meta =93case=94? We could = add extra =93cases=94 as isolated testing exposes problem sets? I think the idea is interesting. What is the advantage of this approach over: * Run fuzzers in isolation. * When a break occurs, isolate the inputs as a new test case for the e= xisting structured test cases. Thanks! - Bret From: tim.lewis@insyde.com Sent: Tuesday, July 28, 2020 10:13 AM To: devel@edk2.groups.io; spbrogan@outlook.co= m; Ni, Ray Cc: Kinney, Michael D; 'Ming Shao'; Dong, Eric; 'Laszlo Er= sek'; Sean Brogan; Bret Barkelew; Yao, Jiewen Subject: [EXTERNAL] RE: [edk2-devel] [PATCH v4] UefiCpuPkg/MtrrLib/UnitTes= t: Add host based unit test Sean -- What I have seen done for fuzz testing is to (a) report the seed used to i= nitialize the RNG in the log and then (b) provide an option to force the se= ed to that value. Using a static seed might actually be the default for CI = runs, but stand-alone runs could use a random value. Just a thought. Tim -----Original Message----- From: devel@edk2.groups.io On Behalf Of Sean Sent: Tuesday, July 28, 2020 9:38 AM To: devel@edk2.groups.io; ray.ni@intel.com Cc: Michael D Kinney ; Ming Shao ; Eric Dong ; Laszlo Ersek = ; Sean Brogan ; Bret Barkelew ; Jiewen Yao Subject: Re: [edk2-devel] [PATCH v4] UefiCpuPkg/MtrrLib/UnitTest: Add host= based unit test Ray, I worry that this style of testing will lead to inconsistant results. Generating random test cases means that the test cases on any given run could find a bug in this code without this code changing. I think this type of testing (fuzz testing like) is great but I think we might want to consider this a different test type and treat it differently. For unit testing the mtrr lib it would make more sense to identify a few unique passing and failing tests and statically add those. If there are edge cases or more cases needed to get full code coverage then developing those would be great. Another point is once we start tracking code coverage your random test generation will lead to different results which will make it hard to track the metrics reliably. Finally, if edk2 community wants to support fuzz testing (which i think is good) we should add details about how to add fuzz testing to edk2 and how to exclude it from PR/CI test runs. Thoughts? Thanks Sean On 7/28/2020 1:43 AM, Ni, Ray wrote: > 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 > --- > .../MtrrLib/UnitTest/MtrrLibUnitTest.c | 1139 +++++++++++++++++ > .../MtrrLib/UnitTest/MtrrLibUnitTest.h | 182 +++ > .../MtrrLib/UnitTest/MtrrLibUnitTestHost.inf | 39 + > UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c | 923 +++++++++++++ > UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc | 31 + > UefiCpuPkg/UefiCpuPkg.ci.yaml | 12 +- > 6 files changed, 2325 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/MtrrLibUnitTest= Host.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/Uef= iCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c > new file mode 100644 > index 0000000000..123e1c741a > --- /dev/null > +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c > @@ -0,0 +1,1139 @@ > +/** @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",= "WP", "WB" }; > > + > > +/** > > + Compare the actual memory ranges against expected memory ranges and r= eturn 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, ActualRan= ges[Index].BaseAddress); > > + UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].Length, ActualRanges[I= ndex].Length); > > + UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].Type, ActualRanges[Ind= ex].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].Bas= eAddress, 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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_= MTRR]; > > + MTRR_MEMORY_RANGE ExpectedMemoryRanges[MTRR_NUMBER_OF_F= IXED_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1]; > > + UINT32 ExpectedVariableMtrrUsage; > > + UINTN ExpectedMemoryRangesCount; > > + > > + MTRR_MEMORY_RANGE ActualMemoryRanges[MTRR_NUMBER_OF_FIX= ED_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 (PcdCpuNumberOfR= eservedVariableMtrrs), > > + &UcCount, &WtCount, &WbCount, &WpCount, &WcCount > > + ); > > + GenerateValidAndConfigurableMtrrPairs ( > > + SystemParameter->PhysicalAddressBits, RawMtrrRange, > > + UcCount, WtCount, WbCount, WpCount, WcCount > > + ); > > + > > + ExpectedVariableMtrrUsage =3D UcCount + WtCount + WbCount + WpCount += WcCount; > > + 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, WcCo= unt > > + ); > > + UT_LOG_INFO ("--- Expected Memory Ranges [%d] ---\n", ExpectedMemoryR= angesCount); > > + 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],= Scratch, &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->PhysicalAddre= ssBits, SystemParameter->VariableMtrrCount, > > + &LocalMtrrs, ActualMemoryRanges, &ActualMemoryRangesCount, &Actua= lVariableMtrrUsage > > + ); > > + > > + UT_LOG_INFO ("--- Actual Memory Ranges [%d] ---\n", ActualMemoryRan= gesCount); > > + DumpMemoryRanges (ActualMemoryRanges, ActualMemoryRangesCount); > > + VerifyMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesCount= , ActualMemoryRanges, ActualMemoryRangesCount); > > + UT_ASSERT_TRUE (ExpectedVariableMtrrUsage >=3D ActualVariableMtrrUs= age); > > + > > + 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].Ty= pe > > + ); > > + UT_ASSERT_TRUE (RETURN_ERROR (Status)); > > + } > > + > > + ScratchSize =3D 0; > > + Status =3D MtrrSetMemoryAttributesInMtrrSettings (NULL, NULL, &Scratc= hSize, 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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 (Sys= temParameter)); > > + // > > + // 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 MTRR= s. > > + // > > + 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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 (Sys= temParameter)); > > + // > > + // If MTRR capability off in CPUID leaf, then the count is always 0. > > + // > > + SystemParameter.MtrrSupported =3D FALSE; > > + for (SystemParameter.VariableMtrrCount =3D 1; SystemParameter.Variabl= eMtrrCount <=3D MTRR_NUMBER_OF_VARIABLE_MTRR; SystemParameter.VariableMtrrC= ount++) { > > + 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 = ASSERT() > > + // is generated. > > + // > > + SystemParameter.MtrrSupported =3D TRUE; > > + for (SystemParameter.VariableMtrrCount =3D 1; SystemParameter.Variabl= eMtrrCount <=3D MTRR_NUMBER_OF_VARIABLE_MTRR; SystemParameter.VariableMtrrC= ount++) { > > + InitializeMtrrRegs (&SystemParameter); > > + Result =3D GetVariableMtrrCount (); > > + UT_ASSERT_EQUAL (Result, SystemParameter.VariableMtrrCount); > > + } > > + > > + // > > + // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER_OF_VARIABL= E_MTRR > > + // > > + 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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 *= ) Context; > > + > > + CopyMem (&SystemParameter, LocalContext->SystemParameter, sizeof (Sys= temParameter)); > > + > > + InitializeMtrrRegs (&SystemParameter); > > + // > > + // Positive test cases for VCNT =3D 10 and Reserved PCD in range 0..1= 0 > > + // > > + for (ReservedMtrrs =3D 0; ReservedMtrrs <=3D SystemParameter.Variable= MtrrCount; ReservedMtrrs++) { > > + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, ReservedMtrrs); > > + Result =3D GetFirmwareVariableMtrrCount (); > > + UT_ASSERT_EQUAL (Result, SystemParameter.VariableMtrrCount - Reserv= edMtrrs); > > + } > > + > > + // > > + // Negative test cases when Reserved PCD is larger than VCNT > > + // > > + for (ReservedMtrrs =3D SystemParameter.VariableMtrrCount + 1; Reserve= dMtrrs <=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_VARIABL= E_MTRR > > + // > > + 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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 (Sys= temParameter)); > > + 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); MsrI= ndex++) { > > + MsrValue =3D 0; > > + for (ByteIndex =3D 0; ByteIndex < sizeof (UINT64); ByteIndex++) { > > + MsrValue =3D MsrValue | LShiftU64 (GenerateRandomCacheType (), = ByteIndex * 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= (FixedSettings)); > > + } > > + > > + // > > + // 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 (= ExpectedFixedSettings)); > > + > > + return UNIT_TEST_PASSED; > > +} > > + > > +/** > > + Unit test of MtrrLib service MtrrGetAllMtrrs() > > + > > + @param[in] Context Ignored > > + > > + @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 faile= d. > > + > > +**/ > > +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 (Sys= temParameter)); > > + InitializeMtrrRegs (&SystemParameter); > > + > > + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++)= { > > + GenerateRandomMtrrPair (SystemParameter.PhysicalAddressBits, Genera= teRandomCacheType (), &VariableMtrr[Index], NULL); > > + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index << 1), VariableMtrr= [Index].Base); > > + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index << 1), VariableMtrr= [Index].Mask); > > + } > > + Result =3D MtrrGetAllMtrrs (&Mtrrs); > > + UT_ASSERT_EQUAL (Result, &Mtrrs); > > + UT_ASSERT_MEM_EQUAL (Mtrrs.Variables.Mtrr, VariableMtrr, sizeof (MTRR= _VARIABLE_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_VARIABL= E_MTRR > > + // > > + 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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 (Sys= temParameter)); > > + 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, Genera= teRandomCacheType (), &Mtrrs.Variables.Mtrr[Index], NULL); > > + } > > + Result =3D MtrrSetAllMtrrs (&Mtrrs); > > + UT_ASSERT_EQUAL (Result, &Mtrrs); > > + > > + UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE), Mtrrs.MtrrDef= Type); > > + 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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_VARIAB= LE_MTRR]; > > + VARIABLE_MTRR VariableMtrr[MTRR_NUMBER_OF_VARIABLE_= MTRR]; > > + 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 (Sys= temParameter)); > > + > > + InitializeMtrrRegs (&SystemParameter); > > + > > + ValidMtrrBitsMask =3D (1ull << SystemParameter.PhysicalAddressBits= ) - 1; > > + ValidMtrrAddressMask =3D ValidMtrrBitsMask & 0xfffffffffffff000ULL; > > + > > + for (Index =3D 0; Index < SystemParameter.VariableMtrrCount; Index++)= { > > + GenerateRandomMtrrPair (SystemParameter.PhysicalAddressBits, Genera= teRandomCacheType (), &VariableSetting[Index], NULL); > > + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index << 1), VariableSett= ing[Index].Base); > > + AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index << 1), VariableSett= ing[Index].Mask); > > + } > > + Result =3D MtrrGetMemoryAttributeInVariableMtrr (ValidMtrrBitsMask, V= alidMtrrAddressMask, 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) & ValidMtrrBit= sMask; > > + 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, V= alidMtrrAddressMask, VariableMtrr); > > + UT_ASSERT_EQUAL (Result, 0); > > + > > + // > > + // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER_OF_VARIABL= E_MTRR > > + // > > + SystemParameter.MtrrSupported =3D TRUE; > > + SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE_MTRR + = 1; > > + InitializeMtrrRegs (&SystemParameter); > > + UT_EXPECT_ASSERT_FAILURE (MtrrGetMemoryAttributeInVariableMtrr (Valid= MtrrBitsMask, 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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 (Sys= temParameter)); > > + // > > + // If MTRRs are supported, then always return the cache type in the M= SR > > + // 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= the test > > + case was successful. > > + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has faile= d. > > + > > +**/ > > +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_= MTRR]; > > + MTRR_MEMORY_RANGE ExpectedMemoryRanges[MTRR_NUMBER_OF_F= IXED_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1]; > > + UINT32 ExpectedVariableMtrrUsage; > > + UINTN ExpectedMemoryRangesCount; > > + > > + MTRR_MEMORY_RANGE ActualMemoryRanges[MTRR_NUMBER_OF_FIX= ED_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 (PcdCpuNumberOfR= eservedVariableMtrrs), > > + &UcCount, &WtCount, &WbCount, &WpCount, &WcCount > > + ); > > + GenerateValidAndConfigurableMtrrPairs ( > > + SystemParameter->PhysicalAddressBits, RawMtrrRange, > > + UcCount, WtCount, WbCount, WpCount, WcCount > > + ); > > + > > + ExpectedVariableMtrrUsage =3D UcCount + WtCount + WbCount + WpCount += WcCount; > > + ExpectedMemoryRangesCount =3D ARRAY_SIZE (ExpectedMemoryRanges); > > + GetEffectiveMemoryRanges ( > > + SystemParameter->DefaultCacheType, > > + SystemParameter->PhysicalAddressBits, > > + RawMtrrRange, ExpectedVariableMtrrUsage, > > + ExpectedMemoryRanges, &ExpectedMemoryRangesCount > > + ); > > + > > + UT_LOG_INFO ("--- Expected Memory Ranges [%d] ---\n", ExpectedMemoryR= angesCount); > > + 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 RET= URN_OUT_OF_RESOURCES || Status =3D=3D RETURN_BUFFER_TOO_SMALL); > > + if (Status =3D=3D RETURN_OUT_OF_RESOURCES || Status =3D=3D RETURN= _BUFFER_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->PhysicalAddre= ssBits, SystemParameter->VariableMtrrCount, > > + &LocalMtrrs, ActualMemoryRanges, &ActualMemoryRangesCount, &Actua= lVariableMtrrUsage > > + ); > > + UT_LOG_INFO ("--- Actual Memory Ranges [%d] ---\n", ActualMemoryRan= gesCount); > > + DumpMemoryRanges (ActualMemoryRanges, ActualMemoryRangesCount); > > + VerifyMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesCount= , ActualMemoryRanges, ActualMemoryRangesCount); > > + UT_ASSERT_TRUE (ExpectedVariableMtrrUsage >=3D ActualVariableMtrrUs= age); > > + > > + ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs)); > > + } > > + > > + return UNIT_TEST_PASSED; > > +} > > + > > + > > +/** > > + Prep routine for UnitTestGetFirmwareVariableMtrrCount(). > > + > > + @param Context Point to a UINT32 data to save the PcdCpuNumberOfRese= rvedVariableMtrrs. > > +**/ > > +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 *= ) Context; > > + LocalContext->NumberOfReservedVariableMtrrs =3D PatchPcdGet32 (PcdCpu= NumberOfReservedVariableMtrrs); > > + return UNIT_TEST_PASSED; > > +} > > + > > +/** > > + Clean up routine for UnitTestGetFirmwareVariableMtrrCount(). > > + > > + @param Context Point to a UINT32 data to save the PcdCpuNumberOfRese= rvedVariableMtrrs. > > +**/ > > +VOID > > +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 *= ) Context; > > + PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, LocalContext->Num= berOfReservedVariableMtrrs); > > +} > > + > > +/** > > + Initialize the unit test framework, suite, and unit tests for the > > + ResetSystemLib and run the ResetSystemLib unit test. > > + > > + @param Iteration Iteration of testing MtrrSetMemoryAttr= ibuteInMtrrSettings > > + and MtrrSetMemoryAttributesInMtrrSetti= ngs using random inputs. > > + > > + @retval EFI_SUCCESS All test cases were dispatched. > > + @retval EFI_OUT_OF_RESOURCES There are not enough resources availab= le 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 GetFirmwareVariable= MtrrCountContext; > > + > > + Context.SystemParameter =3D &mDefaultSyst= emParameter; > > + GetFirmwareVariableMtrrCountContext.SystemParameter =3D &mDefaultSyst= emParameter; > > + Framework =3D NULL; > > + > > + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VER= SION)); > > + > > + // > > + // Setup the test framework for running the tests. > > + // > > + Status =3D InitUnitTestFramework (&Framework, UNIT_TEST_APP_NAME, gEf= iCallerBaseName, 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 AP= I Tests", "MtrrLib.MtrrLib", NULL, NULL); > > + if (EFI_ERROR (Status)) { > > + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for MtrrLib API= Tests\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", UnitTestGetFirmwareVariableMtrrC= ount, SavePcdValue, RestorePcdValue, &GetFirmwareVariableMtrrCountC= ontext); > > + 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", UnitTestMtrrGetMemoryAttributeIn= VariableMtrr, 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);= SystemIndex++) { > > + for (Index =3D 0; Index < Iteration; Index++) { > > + AddTestCase (MtrrApiTests, "Test InvalidMemoryLayouts", = "InvalidMemoryLayouts", UnitTestInvalidMemoryLayou= ts, InitializeSystem, NULL, &mSystemParameters[SystemIndex= ]); > > + AddTestCase (MtrrApiTests, "Test MtrrSetMemoryAttributeInMtrrSett= ings", "MtrrSetMemoryAttributeInMtrrSettings", UnitTestMtrrSetMemoryAttri= buteInMtrrSettings, InitializeSystem, NULL, &mSystemParameters[SystemIndex= ]); > > + AddTestCase (MtrrApiTests, "Test MtrrSetMemoryAttributesInMtrrSet= tings", "MtrrSetMemoryAttributesInMtrrSettings", UnitTestMtrrSetMemoryAttri= butesInMtrrSettings, InitializeSystem, 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/Uef= iCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h > new file mode 100644 > index 0000000000..9750523133 > --- /dev/null > +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h > @@ -0,0 +1,182 @@ > +/** @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 regist= ers initialization. > > +**/ > > +UNIT_TEST_STATUS > > +EFIAPI > > +InitializeMtrrRegs ( > > + IN MTRR_LIB_SYSTEM_PARAMETER *SystemParameter > > + ); > > + > > +/** > > + Initialize the MTRR registers. > > + > > + @param Context System parameter that controls the MTRR registers init= ialization. > > +**/ > > +UNIT_TEST_STATUS > > +EFIAPI > > +InitializeSystem ( > > + IN UNIT_TEST_CONTEXT Context > > + ); > > + > > +/** > > + 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 = used. > > +**/ > > +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-0509084376= AB > > + MODULE_TYPE =3D HOST_APPLICATION > > + VERSION_STRING =3D 1.0 > > + > > +# > > +# The following information is for reference only and not required by t= he 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 ## SO= METIMES_CONSUMES > > diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c b/UefiCpuPkg/= Library/MtrrLib/UnitTest/Support.c > new file mode 100644 > index 0000000000..a7eed45940 > --- /dev/null > +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c > @@ -0,0 +1,923 @@ > +/** @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, CacheWriteP= rotected, 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; > > + > > +/** > > + 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 CPU= ID > > + instruction. This is an optional parameter that may be = NULL. > > + @param Ebx The pointer to the 32-bit EBX value returned by the CPU= ID > > + instruction. This is an optional parameter that may be = NULL. > > + @param Ecx The pointer to the 32-bit ECX value returned by the CPU= ID > > + instruction. This is an optional parameter that may be = NULL. > > + @param Edx The pointer to the 32-bit EDX value returned by the CPU= ID > > + 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 > > + ) > > +{ > > + 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 che= cking is > > + performed on Index, and some Index values may cause CPU exceptions. T= he > > + caller must either guarantee that Index is valid, or the caller must = set up > > + exception handlers to catch the exceptions. This function is only ava= ilable > > + 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= _MTRR << 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 return= s the > > + value. > > + > > + Writes the 64-bit value specified by Value to the MSR specified by In= dex. 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 exceptio= ns. The > > + caller must either guarantee that Index and Value are valid, or the c= aller > > + must establish proper exception handlers. This function is only avail= able 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= _MTRR << 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 the MTRR registers. > > + > > + @param SystemParameter System parameter that controls the MTRR regist= ers initialization. > > +**/ > > +UNIT_TEST_STATUS > > +EFIAPI > > +InitializeMtrrRegs ( > > + IN MTRR_LIB_SYSTEM_PARAMETER *SystemParameter > > + ) > > +{ > > + UINT32 Index; > > + > > + SetMem (mFixedMtrrsValue, sizeof (mFixedMtrrsValue), SystemParameter-= >DefaultCacheType); > > + > > + for (Index =3D 0; Index < ARRAY_SIZE (mVariableMtrrsPhysBase); Index+= +) { > > + mVariableMtrrsPhysBase[Index].Uint64 =3D 0; > > + mVariableMtrrsPhysBase[Index].Bits.Type =3D SystemParameter->D= efaultCacheType; > > + 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 SystemParamet= er->MtrrSupported; > > + mCpuidVirPhyAddressSizeEax.Bits.PhysicalAddressBits =3D SystemParamet= er->PhysicalAddressBits; > > + > > + // > > + // Hook BaseLib functions used by MtrrLib that require some emulation= . > > + // > > + gUnitTestHostBaseLib.X86->AsmCpuid =3D UnitTestMtrrLibAsmCpuid; > > + gUnitTestHostBaseLib.X86->AsmReadMsr64 =3D UnitTestMtrrLibAsmReadMsr= 64; > > + gUnitTestHostBaseLib.X86->AsmWriteMsr64 =3D UnitTestMtrrLibAsmWriteMs= r64; > > + > > + return UNIT_TEST_PASSED; > > +} > > + > > +/** > > + Initialize the MTRR registers. > > + > > + @param Context System parameter that controls the MTRR registers init= ialization. > > +**/ > > +UNIT_TEST_STATUS > > +EFIAPI > > +InitializeSystem ( > > + IN UNIT_TEST_CONTEXT Context > > + ) > > +{ > > + return InitializeMtrrRegs ((MTRR_LIB_SYSTEM_PARAMETER *) Context); > > +} > > + > > +/** > > + 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 = used. > > +**/ > > +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[Ind= ex].Mask)->Bits.V =3D=3D 1) { > > + RawMemoryRanges[*MtrrCount].BaseAddress =3D Mtrrs->Variables.Mtrr= [Index].Base & MtrrValidAddressMask; > > + RawMemoryRanges[*MtrrCount].Type =3D > > + ((MSR_IA32_MTRR_PHYSBASE_REGISTER *) &Mtrrs->Variables.Mtrr[Ind= ex].Base)->Bits.Type; > > + RawMemoryRanges[*MtrrCount].Length =3D > > + ((~(Mtrrs->Variables.Mtrr[Index].Mask & MtrrValidAddressMask)= ) & MtrrValidBitsMask) + 1; > > + (*MtrrCount)++; > > + } > > + } > > + > > + GetEffectiveMemoryRanges (DefaultType, PhysicalAddressBits, RawMemory= Ranges, *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)) + S= tart; > > +} > > + > > +/** > > + 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)) + S= tart; > > +} > > + > > +/** > > + 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 - Base= Shift)); > > + RangeBase =3D RandomBoundary << BaseShift; > > + } while (RangeBase < SIZE_1MB || RangeBase > MaxPhysicalAddress - 1); > > + > > + PhysBasePhyMaskValidBitsMask =3D (MaxPhysicalAddress - 1) & 0xfffffff= ffffff000ULL; > > + > > + 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) & PhysBasePhyMaskValidBitsM= ask; > > + > > + 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[Co= unt].BaseAddress < Range->BaseAddress + Range->Length) > > + || (Ranges[Count].BaseAddress <=3D Range->BaseAddress && Range->Ba= seAddress < 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, NUL= L, &RawMemoryRanges[Index]); > > + } > > + > > + for (Index =3D UcCount + WtCount; Index < UcCount + WtCount + WbCount= ; Index++) { > > + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteBack, NULL, = &RawMemoryRanges[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, N= ULL, &RawMemoryRanges[Index]); > > + while (RangesOverlap (&RawMemoryRanges[Index], &RawMemoryRanges[UcC= ount], WtCount + WbCount)) { > > + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteProtected,= NULL, &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, N= ULL, &RawMemoryRanges[Index]); > > + while (RangesOverlap (&RawMemoryRanges[Index], &RawMemoryRanges[UcC= ount], WtCount + WbCount + WpCount)) { > > + GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteCombining,= NULL, &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, *Coun= t); > > + } > > + *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.Base= Address + 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 = ranges. > > +**/ > > +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= most with 2 more range entries. > > + NewRanges =3D (MTRR_MEMORY_RANGE *) calloc (NewRangesCount= AtMost, sizeof (MTRR_MEMORY_RANGE)); > > + OldRanges =3D *EffectiveMtrrMemoryRanges; > > + if (OldRanges[0].BaseAddress > 0) { > > + NewRanges[NewRangesCountActual].BaseAddress =3D 0; > > + NewRanges[NewRangesCountActual].Length =3D OldRanges[0].BaseAd= dress; > > + 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= first before generate a new NewRange. > > + { > > + CurrentRangeInNewRanges =3D &NewRanges[NewRangesCountActual - 1]; > > + } > > + if (CurrentRangeInNewRanges !=3D NULL && CurrentRangeInNewRanges->T= ype =3D=3D CurrentRangeTypeInOldRanges) { > > + CurrentRangeInNewRanges->Length +=3D OldRanges[OldRangesIndex].Le= ngth; > > + } else { > > + NewRanges[NewRangesCountActual].BaseAddress =3D OldRanges[OldRang= esIndex].BaseAddress; > > + NewRanges[NewRangesCountActual].Length +=3D OldRanges[OldRang= esIndex].Length; > > + NewRanges[NewRangesCountActual].Type =3D CurrentRangeTypeI= nOldRanges; > > + while (OldRangesIndex + 1 < *EffectiveMtrrMemoryRangesCount && Ol= dRanges[OldRangesIndex + 1].Type =3D=3D CurrentRangeTypeInOldRanges) > > + { > > + OldRangesIndex++; > > + NewRanges[NewRangesCountActual].Length +=3D OldRanges[OldRanges= Index].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 - CurrentRangeInNe= wRanges->BaseAddress + 1; > > + } else { > > + NewRanges[NewRangesCountActual].BaseAddress =3D OldLastRange.Base= Address + OldLastRange.Length; > > + NewRanges[NewRangesCountActual].Length =3D MaxAddress - NewRanges= [NewRangesCountActual].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 (UINT= 64)); > > + AllRangePiecesCountMax =3D RawMemoryRangeCount * 3 + 1; > > + AllRangePieces =3D calloc (AllRangePiecesCountMax, sizeof = (MTRR_MEMORY_RANGE)); > > + CollectEndpoints (AllEndPointsInclusive, &AllEndPointsCount, RawMemor= yRanges, RawMemoryRangeCount); > > + > > + for (Index =3D 0, AllRangePiecesCountActual =3D 0; Index < AllEndPoin= tsCount - 1; Index++) { > > + OverlapBitFlag1 =3D GetOverlapBitFlag (RawMemoryRanges, RawMemoryRa= ngeCount, AllEndPointsInclusive[Index]); > > + OverlapBitFlag2 =3D GetOverlapBitFlag (RawMemoryRanges, RawMemoryRa= ngeCount, AllEndPointsInclusive[Index + 1]); > > + OverlapFlagRelation =3D CheckOverlapBitFlagsRelation (OverlapBitFla= g1, OverlapBitFlag2); > > + switch (OverlapFlagRelation) { > > + case 0: // [1, 2] > > + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEn= dPointsInclusive[Index]; > > + AllRangePieces[AllRangePiecesCountActual].Length =3D AllEn= dPointsInclusive[Index + 1] - AllEndPointsInclusive[Index] + 1; > > + AllRangePiecesCountActual++; > > + break; > > + case 1: // [1, 2) > > + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEn= dPointsInclusive[Index]; > > + AllRangePieces[AllRangePiecesCountActual].Length =3D (AllE= ndPointsInclusive[Index + 1] - 1) - AllEndPointsInclusive[Index] + 1; > > + AllRangePiecesCountActual++; > > + break; > > + case 2: // (1, 2] > > + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEn= dPointsInclusive[Index] + 1; > > + AllRangePieces[AllRangePiecesCountActual].Length =3D AllEn= dPointsInclusive[Index + 1] - (AllEndPointsInclusive[Index] + 1) + 1; > > + AllRangePiecesCountActual++; > > + > > + if (!IsEndpointInRanges (AllEndPointsInclusive[Index], AllRange= Pieces, AllRangePiecesCountActual)) { > > + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D All= EndPointsInclusive[Index]; > > + AllRangePieces[AllRangePiecesCountActual].Length =3D 1; > > + AllRangePiecesCountActual++; > > + } > > + break; > > + case 3: // (1, 2) > > + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D AllEn= dPointsInclusive[Index] + 1; > > + AllRangePieces[AllRangePiecesCountActual].Length =3D (AllE= ndPointsInclusive[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], AllRange= Pieces, AllRangePiecesCountActual)) { > > + AllRangePieces[AllRangePiecesCountActual].BaseAddress =3D All= EndPointsInclusive[Index]; > > + AllRangePieces[AllRangePiecesCountActual].Length =3D 1; > > + AllRangePiecesCountActual++; > > + } > > + break; > > + default: > > + ASSERT (FALSE); > > + } > > + } > > + > > + for (Index =3D 0; Index < AllRangePiecesCountActual; Index++) { > > + DetermineMemoryCacheType (DefaultType, &AllRangePieces[Index], RawM= emoryRanges, RawMemoryRangeCount); > > + } > > + > > + CompactAndExtendEffectiveMtrrMemoryRanges (DefaultType, PhysicalAddre= ssBits, &AllRangePieces, &AllRangePiecesCountActual); > > + ASSERT (*MemoryRangeCount >=3D AllRangePiecesCountActual); > > + memcpy (MemoryRanges, AllRangePieces, AllRangePiecesCountActual * siz= eof (MTRR_MEMORY_RANGE)); > > + *MemoryRangeCount =3D AllRangePiecesCountActual; > > + > > + free (AllEndPointsInclusive); > > + free (AllRangePieces); > > +} > > diff --git a/UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc b/UefiCpuPkg/Test/Ue= fiCpuPkgHostTest.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.ya= ml > 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 dupli= cation for gEfiFirmwareVolumeTopFileGuid > > "IgnoreGuidValue": [], > --_000_CY4PR21MB07430EEAF012BC185B3DC28AEF730CY4PR21MB0743namp_ Content-Type: text/html; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable

In this strategy, the seed would function like a me= ta =93case=94? We could add extra =93cases=94 as isolated testing exposes p= roblem sets?

 

I think the idea is interesting.

 

What is the advantage of this approach over:

  • Run fuzzers in isolation.
  • When a break occurs, isolate = the inputs as a new test case for the existing structured test cases.
  • <= /ul>

     

    Thanks!

     

    - Bret

     

    From: tim.lewis@insyde.com
    Sent: Tuesday, July 28, 2020 10:13 AM
    To: devel@edk2.groups.io; spbrogan@outlook.com; Ni, Ray<= br> Cc: Kinney, Michael D= ; 'Ming Shao'; Dong, Eric; 'Laszlo Ersek'; Sean Brog= an; Bret Barkelew; Yao, Jiewen=
    Subject: [EXTERNAL] RE: [edk2-devel] [PATCH v4] UefiCpuPkg/MtrrLib/= UnitTest: Add host based unit test

     

    Sean --

    What I have seen done for fuzz testing is to (a) report the seed used to i= nitialize the RNG in the log and then (b) provide an option to force the se= ed to that value. Using a static seed might actually be the default for CI = runs, but stand-alone runs could use a random value.

    Just a thought.

    Tim

    -----Original Message-----
    From: devel@edk2.groups.io <devel@edk2.groups.io> On Behalf Of Sean<= br> Sent: Tuesday, July 28, 2020 9:38 AM
    To: devel@edk2.groups.io; ray.ni@intel.com
    Cc: Michael D Kinney <michael.d.kinney@intel.com>; Ming Shao <min= g.shao@intel.com>; Eric Dong <eric.dong@intel.com>; Laszlo Ersek &= lt;lersek@redhat.com>; Sean Brogan <sean.brogan@microsoft.com>; Br= et Barkelew <Bret.Barkelew@microsoft.com>; Jiewen Yao <jiewen.yao@= intel.com>
    Subject: Re: [edk2-devel] [PATCH v4] UefiCpuPkg/MtrrLib/UnitTest: Add host= based unit test

    Ray,

    I worry that this style of testing will lead to inconsistant results.
    Generating random test cases means that the test cases on any given run could find a bug in this code without this code changing.   I th= ink this
    type of testing (fuzz testing like) is great but I think we might want to consider this a different test type and treat it differently.

    For unit testing the mtrr lib it would make more sense to identify a few <= br> unique passing and failing tests and statically add those.  If there = are
    edge cases or more cases needed to get full code coverage then
    developing those would be great.

    Another point is once we start tracking code coverage your random test generation will lead to different results which will make it hard to
    track the metrics reliably.

    Finally, if edk2 community wants to support fuzz testing (which i think is good) we should add details about how to add fuzz testing to edk2 and <= br>   how to exclude it from PR/CI test runs.

    Thoughts?

    Thanks
    Sean




    On 7/28/2020 1:43 AM, Ni, Ray wrote:
    > 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 <ray.ni@intel.com>
    > Signed-off-by: Michael D Kinney <michael.d.kinney@intel.com> > Signed-off-by: Ming Shao <ming.shao@intel.com>
    > Cc: Michael D Kinney <michael.d.kinney@intel.com>
    > Cc: Eric Dong <eric.dong@intel.com>
    > Cc: Laszlo Ersek <lersek@redhat.com>
    > Cc: Ming Shao <ming.shao@intel.com>
    > Cc: Sean Brogan <sean.brogan@microsoft.com>
    > Cc: Bret Barkelew <Bret.Barkelew@microsoft.com>
    > Cc: Jiewen Yao <jiewen.yao@intel.com>
    > ---
    >   .../MtrrLib/UnitTest/MtrrLibUnitTest.c   &= nbsp;    | 1139 +++++++++++++++++
    >   .../MtrrLib/UnitTest/MtrrLibUnitTest.h   &= nbsp;    |  182 +++
    >   .../MtrrLib/UnitTest/MtrrLibUnitTestHost.inf  | = ;  39 +
    >   UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c |  923= +++++++++++++
    >   UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc   &= nbsp;    |   31 +
    >   UefiCpuPkg/UefiCpuPkg.ci.yaml    &nbs= p;            | = ;  12 +-
    >   6 files changed, 2325 insertions(+), 1 deletion(-)
    >   create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/Mt= rrLibUnitTest.c
    >   create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/Mt= rrLibUnitTest.h
    >   create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/Mt= rrLibUnitTestHost.inf
    >   create mode 100644 UefiCpuPkg/Library/MtrrLib/UnitTest/Su= pport.c
    >   create mode 100644 UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc=
    >
    > diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c b/= UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c
    > new file mode 100644
    > index 0000000000..123e1c741a
    > --- /dev/null
    > +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.c
    > @@ -0,0 +1,1139 @@
    > +/** @file
    >
    > +  Unit tests of the MtrrLib instance of the MtrrLib class
    >
    > +
    >
    > +  Copyright (c) 2020, Intel Corporation. All rights reserved.&l= t;BR>
    >
    > +  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,    &nbs= p; 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,    &nbs= p; 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,    &nbs= p; 12 },
    >
    > +  { 48, TRUE, TRUE, CacheWriteThrough,   12 },
    >
    > +  { 48, TRUE, TRUE, CacheWriteProtected, 12 },
    >
    > +  { 48, TRUE, TRUE, CacheWriteCombining, 12 },
    >
    > +};
    >
    > +
    >
    > +UINT32          &n= bsp;         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_MT= RR),
    >
    > +  "gFixedMtrrIndex does NOT contain all the fixed MTRRs!&q= uot;
    >
    > +  );
    >
    > +
    >
    > +//
    >
    > +// 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() t= est.
    >
    > +//
    >
    > +typedef struct {
    >
    > +  UINT32         &= nbsp;           &nbs= p;    NumberOfReservedVariableMtrrs;
    >
    > +  CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter;
    >
    > +} MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT;
    >
    > +
    >
    > +STATIC CHAR8 *mCacheDescription[] =3D { "UC", "WC&quo= t;, "N/A", "N/A", "WT", "WP", "= ;WB" };
    >
    > +
    >
    > +/**
    >
    > +  Compare the actual memory ranges against expected memory rang= es and return PASS when they match.
    >
    > +
    >
    > +  @param ExpectedMemoryRanges     Expected = memory ranges.
    >
    > +  @param ExpectedMemoryRangeCount Count of expected memory rang= es.
    >
    > +  @param ActualRanges       =       Actual memory ranges.
    >
    > +  @param ActualRangeCount      &n= bsp;  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].Base= Address, ActualRanges[Index].BaseAddress);
    >
    > +    UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].Leng= th, ActualRanges[Index].Length);
    >
    > +    UT_ASSERT_EQUAL (ExpectedMemoryRanges[Index].Type= , ActualRanges[Index].Type);
    >
    > +  }
    >
    > +
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Dump the memory ranges.
    >
    > +
    >
    > +  @param Ranges       Memory rang= es to dump.
    >
    > +  @param RangeCount   Count of memory ranges.
    >
    > +**/
    >
    > +VOID
    >
    > +DumpMemoryRanges (
    >
    > +  MTRR_MEMORY_RANGE    *Ranges,
    >
    > +  UINTN         &n= bsp;      RangeCount
    >
    > +  )
    >
    > +{
    >
    > +  UINTN     Index;
    >
    > +  for (Index =3D 0; Index < RangeCount; Index++) {
    >
    > +    UT_LOG_INFO ("\t{ 0x%016llx, 0x%016llx, %a }= ,\n", Ranges[Index].BaseAddress, Ranges[Index].Length, mCacheDescripti= on[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 Throug= h type.
    >
    > +  @param WbCount    Return count of Write Back t= ype.
    >
    > +  @param WpCount    Return count of Write Protec= ted type.
    >
    > +  @param WcCount    Return count of Write Combin= ing 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 (CountPer= Type) - 1)]))++;
    >
    > +  }
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Unit test of MtrrLib service MtrrSetMemoryAttribute()
    >
    > +
    >
    > +  @param[in]  Context    Ignored
    >
    > +
    >
    > +  @retval  UNIT_TEST_PASSED     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestMtrrSetMemoryAttributesInMtrrSettings (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter;
    >
    > +  RETURN_STATUS        =            Status;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    UcCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WtCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WbCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WpCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WcCount;
    >
    > +
    >
    > +  UINT32         &= nbsp;           &nbs= p;    MtrrIndex;
    >
    > +  UINT8         &n= bsp;            = ;     *Scratch;
    >
    > +  UINTN         &n= bsp;            = ;     ScratchSize;
    >
    > +  MTRR_SETTINGS        =            LocalMtrrs; >
    > +
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       RawMtrrRange[MTRR_NUMBER_OF_VARIAB= LE_MTRR];
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       ExpectedMemoryRanges[MTRR_NUMBER_O= F_FIXED_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1];
    >
    > +  UINT32         &= nbsp;           &nbs= p;    ExpectedVariableMtrrUsage;
    >
    > +  UINTN         &n= bsp;            = ;     ExpectedMemoryRangesCount;
    >
    > +
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       ActualMemoryRanges[MTRR_NUMBER_OF_= FIXED_MTRR   * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR= + 1];
    >
    > +  UINT32         &= nbsp;           &nbs= p;    ActualVariableMtrrUsage;
    >
    > +  UINTN         &n= bsp;            = ;     ActualMemoryRangesCount;
    >
    > +
    >
    > +  MTRR_SETTINGS        =      *Mtrrs[2];
    >
    > +
    >
    > +  SystemParameter =3D (MTRR_LIB_SYSTEM_PARAMETER *) Context; >
    > +  GenerateRandomMemoryTypeCombination (
    >
    > +    SystemParameter->VariableMtrrCount - PatchPcdG= et32 (PcdCpuNumberOfReservedVariableMtrrs),
    >
    > +    &UcCount, &WtCount, &WbCount, &Wp= Count, &WcCount
    >
    > +    );
    >
    > +  GenerateValidAndConfigurableMtrrPairs (
    >
    > +    SystemParameter->PhysicalAddressBits, RawMtrrR= ange,
    >
    > +    UcCount, WtCount, WbCount, WpCount, WcCount
    >
    > +    );
    >
    > +
    >
    > +  ExpectedVariableMtrrUsage =3D UcCount + WtCount + WbCount + W= pCount + WcCount;
    >
    > +  ExpectedMemoryRangesCount =3D ARRAY_SIZE (ExpectedMemoryRange= s);
    >
    > +  GetEffectiveMemoryRanges (
    >
    > +    SystemParameter->DefaultCacheType,
    >
    > +    SystemParameter->PhysicalAddressBits,
    >
    > +    RawMtrrRange, ExpectedVariableMtrrUsage,
    >
    > +    ExpectedMemoryRanges, &ExpectedMemoryRangesCo= unt
    >
    > +    );
    >
    > +
    >
    > +  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, WbCo= unt, WpCount, WcCount
    >
    > +    );
    >
    > +  UT_LOG_INFO ("--- Expected Memory Ranges [%d] ---\n"= ;, ExpectedMemoryRangesCount);
    >
    > +  DumpMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesC= ount);
    >
    > +
    >
    > +  //
    >
    > +  // Default cache type is always an INPUT
    >
    > +  //
    >
    > +  ZeroMem (&LocalMtrrs, sizeof (LocalMtrrs));
    >
    > +  LocalMtrrs.MtrrDefType =3D MtrrGetDefaultMemoryType ();
    >
    > +  ScratchSize        &n= bsp;   =3D SCRATCH_BUFFER_SIZE;
    >
    > +  Mtrrs[0]         = ;      =3D &LocalMtrrs;
    >
    > +  Mtrrs[1]         = ;      =3D NULL;
    >
    > +
    >
    > +  for (MtrrIndex =3D 0; MtrrIndex < ARRAY_SIZE (Mtrrs); Mtrr= Index++) {
    >
    > +    Scratch =3D calloc (ScratchSize, sizeof (UINT8));=
    >
    > +    Status =3D MtrrSetMemoryAttributesInMtrrSettings = (Mtrrs[MtrrIndex], Scratch, &ScratchSize, ExpectedMemoryRanges, Expecte= dMemoryRangesCount);
    >
    > +    if (Status =3D=3D RETURN_BUFFER_TOO_SMALL) {
    >
    > +      Scratch =3D realloc (Scratch, Scratch= Size);
    >
    > +      Status =3D MtrrSetMemoryAttributesInM= trrSettings (Mtrrs[MtrrIndex], Scratch, &ScratchSize, ExpectedMemoryRan= ges, ExpectedMemoryRangesCount);
    >
    > +    }
    >
    > +    UT_ASSERT_STATUS_EQUAL (Status, RETURN_SUCCESS);<= br> >
    > +
    >
    > +    if (Mtrrs[MtrrIndex] =3D=3D NULL) {
    >
    > +      ZeroMem (&LocalMtrrs, sizeof (Loc= alMtrrs));
    >
    > +      MtrrGetAllMtrrs (&LocalMtrrs); >
    > +    }
    >
    > +    ActualMemoryRangesCount =3D ARRAY_SIZE (ActualMem= oryRanges);
    >
    > +    CollectTestResult (
    >
    > +      SystemParameter->DefaultCacheType,= SystemParameter->PhysicalAddressBits, SystemParameter->VariableMtrrC= ount,
    >
    > +      &LocalMtrrs, ActualMemoryRanges, = &ActualMemoryRangesCount, &ActualVariableMtrrUsage
    >
    > +      );
    >
    > +
    >
    > +    UT_LOG_INFO ("--- Actual Memory Ranges [%d] = ---\n", ActualMemoryRangesCount);
    >
    > +    DumpMemoryRanges (ActualMemoryRanges, ActualMemor= yRangesCount);
    >
    > +    VerifyMemoryRanges (ExpectedMemoryRanges, Expecte= dMemoryRangesCount, ActualMemoryRanges, 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 reject= ed.
    >
    > +
    >
    > +  @param Context   Pointer to MTRR_LIB_SYSTEM_PARAMET= ER.
    >
    > +
    >
    > +  @return Test status.
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestInvalidMemoryLayouts (
    >
    > +  IN UNIT_TEST_CONTEXT       = ;   Context
    >
    > +  )
    >
    > +{
    >
    > +  CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter;
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       Ranges[MTRR_NUMBER_OF_VARIABLE_MTR= R * 2 + 1];
    >
    > +  UINTN         &n= bsp;            = ;     RangeCount;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    MaxAddress;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    Index;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    BaseAddress;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    Length;
    >
    > +  RETURN_STATUS        =            Status;
    >
    > +  UINTN         &n= bsp;            = ;     ScratchSize;
    >
    > +
    >
    > +  SystemParameter =3D (MTRR_LIB_SYSTEM_PARAMETER *) Context; >
    > +
    >
    > +  RangeCount =3D Random32 (1, ARRAY_SIZE (Ranges));
    >
    > +  MaxAddress =3D 1ull << SystemParameter->PhysicalAddr= essBits;
    >
    > +
    >
    > +  for (Index =3D 0; Index < RangeCount; Index++) {
    >
    > +    do {
    >
    > +      BaseAddress =3D Random64 (0, MaxAddre= ss);
    >
    > +      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     &= nbsp;  =3D GenerateRandomCacheType ();
    >
    > +
    >
    > +    Status =3D MtrrSetMemoryAttribute (
    >
    > +      Ranges[Index].BaseAddress, Ranges[Ind= ex].Length, Ranges[Index].Type
    >
    > +      );
    >
    > +    UT_ASSERT_TRUE (RETURN_ERROR (Status));
    >
    > +  }
    >
    > +
    >
    > +  ScratchSize =3D 0;
    >
    > +  Status =3D MtrrSetMemoryAttributesInMtrrSettings (NULL, NULL,= &ScratchSize, 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     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestIsMtrrSupported (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER  SystemParameter;
    >
    > +  MTRR_LIB_TEST_CONTEXT      *LocalCon= text;
    >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +  //
    >
    > +  // 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 fi= xed 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     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestGetVariableMtrrCount (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  UINT32         &= nbsp;          Result;
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER SystemParameter;
    >
    > +  MTRR_LIB_TEST_CONTEXT     *LocalContext;<= br> >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +  //
    >
    > +  // If MTRR capability off in CPUID leaf, then the count is al= ways 0.
    >
    > +  //
    >
    > +  SystemParameter.MtrrSupported =3D FALSE;
    >
    > +  for (SystemParameter.VariableMtrrCount =3D 1; SystemParameter= .VariableMtrrCount <=3D MTRR_NUMBER_OF_VARIABLE_MTRR; SystemParameter.Va= riableMtrrCount++) {
    >
    > +    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_MTR= R, then an ASSERT()
    >
    > +  // is generated.
    >
    > +  //
    >
    > +  SystemParameter.MtrrSupported =3D TRUE;
    >
    > +  for (SystemParameter.VariableMtrrCount =3D 1; SystemParameter= .VariableMtrrCount <=3D MTRR_NUMBER_OF_VARIABLE_MTRR; SystemParameter.Va= riableMtrrCount++) {
    >
    > +    InitializeMtrrRegs (&SystemParameter);
    >
    > +    Result =3D GetVariableMtrrCount ();
    >
    > +    UT_ASSERT_EQUAL (Result, SystemParameter.Variable= MtrrCount);
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER= _OF_VARIABLE_MTRR
    >
    > +  //
    >
    > +  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     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestGetFirmwareVariableMtrrCount (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  UINT32         &= nbsp;           &nbs= p;            &= nbsp;         Result;
    >
    > +  UINT32         &= nbsp;           &nbs= p;            &= nbsp;         ReservedMtrrs;
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER      =             &nb= sp;      SystemParameter;
    >
    > +  MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT *LocalConte= xt;
    >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_C= ONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +  //
    >
    > +  // Positive test cases for VCNT =3D 10 and Reserved PCD in ra= nge 0..10
    >
    > +  //
    >
    > +  for (ReservedMtrrs =3D 0; ReservedMtrrs <=3D SystemParamet= er.VariableMtrrCount; ReservedMtrrs++) {
    >
    > +    PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrr= s, ReservedMtrrs);
    >
    > +    Result =3D GetFirmwareVariableMtrrCount ();
    >
    > +    UT_ASSERT_EQUAL (Result, SystemParameter.Variable= MtrrCount - ReservedMtrrs);
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // Negative test cases when Reserved PCD is larger than VCNT<= br> >
    > +  //
    >
    > +  for (ReservedMtrrs =3D SystemParameter.VariableMtrrCount + 1;= ReservedMtrrs <=3D 255; ReservedMtrrs++) {
    >
    > +    PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrr= s, ReservedMtrrs);
    >
    > +    Result =3D GetFirmwareVariableMtrrCount ();
    >
    > +    UT_ASSERT_EQUAL (Result, 0);
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // Negative test cases when Reserved PCD is larger than VCNT<= br> >
    > +  //
    >
    > +  PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, MAX_UINT3= 2);
    >
    > +  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_MTRR
    >
    > +  //
    >
    > +  SystemParameter.FixedMtrrSupported =3D TRUE;
    >
    > +  SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE= _MTRR + 1;
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +  UT_EXPECT_ASSERT_FAILURE (GetFirmwareVariableMtrrCount (), NU= LL);
    >
    > +
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Unit test of MtrrLib service MtrrGetMemoryAttribute()
    >
    > +
    >
    > +  @param[in]  Context    Ignored
    >
    > +
    >
    > +  @retval  UNIT_TEST_PASSED     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion 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     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestMtrrGetFixedMtrr (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_FIXED_SETTINGS       *Resu= lt;
    >
    > +  MTRR_FIXED_SETTINGS       Expec= tedFixedSettings;
    >
    > +  MTRR_FIXED_SETTINGS       Fixed= Settings;
    >
    > +  UINTN         &n= bsp;           Index;
    >
    > +  UINTN         &n= bsp;           MsrIndex;<= br> >
    > +  UINTN         &n= bsp;           ByteIndex;=
    >
    > +  UINT64         &= nbsp;          MsrValue;
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER SystemParameter;
    >
    > +  MTRR_LIB_TEST_CONTEXT     *LocalContext;<= br> >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +  //
    >
    > +  // Set random cache type to different ranges under 1MB and ma= ke sure
    >
    > +  // the fixed MTRR settings are expected.
    >
    > +  // Try 100 times.
    >
    > +  //
    >
    > +  for (Index =3D 0; Index < 100; Index++) {
    >
    > +    for (MsrIndex =3D 0; MsrIndex < ARRAY_SIZE (mF= ixedMtrrsIndex); MsrIndex++) {
    >
    > +      MsrValue =3D 0;
    >
    > +      for (ByteIndex =3D 0; ByteIndex < = sizeof (UINT64); ByteIndex++) {
    >
    > +        MsrValue =3D MsrValue | L= ShiftU64 (GenerateRandomCacheType (), ByteIndex * 8);
    >
    > +      }
    >
    > +      ExpectedFixedSettings.Mtrr[MsrIndex] = = =3D MsrValue;
    >
    > +      AsmWriteMsr64 (mFixedMtrrsIndex[MsrIn= dex], MsrValue);
    >
    > +    }
    >
    > +
    >
    > +    Result =3D MtrrGetFixedMtrr (&FixedSettings);=
    >
    > +    UT_ASSERT_EQUAL (Result, &FixedSettings);
    >
    > +    UT_ASSERT_MEM_EQUAL (&FixedSettings, &Exp= ectedFixedSettings, sizeof (FixedSettings));
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // Negative test case when MTRRs are not supported
    >
    > +  //
    >
    > +  SystemParameter.MtrrSupported =3D FALSE;
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +
    >
    > +  ZeroMem (&FixedSettings, sizeof (FixedSettings));
    >
    > +  ZeroMem (&ExpectedFixedSettings, sizeof (ExpectedFixedSet= tings));
    >
    > +  Result =3D MtrrGetFixedMtrr (&FixedSettings);
    >
    > +  UT_ASSERT_EQUAL (Result, &FixedSettings);
    >
    > +  UT_ASSERT_MEM_EQUAL (&ExpectedFixedSettings, &FixedSe= ttings, sizeof (ExpectedFixedSettings));
    >
    > +
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Unit test of MtrrLib service MtrrGetAllMtrrs()
    >
    > +
    >
    > +  @param[in]  Context    Ignored
    >
    > +
    >
    > +  @retval  UNIT_TEST_PASSED     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion 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[MT= RR_NUMBER_OF_VARIABLE_MTRR];
    >
    > +  UINT32         &= nbsp;          Index;
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER SystemParameter;
    >
    > +  MTRR_LIB_TEST_CONTEXT     *LocalContext;<= br> >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +
    >
    > +  for (Index =3D 0; Index < SystemParameter.VariableMtrrCoun= t; Index++) {
    >
    > +    GenerateRandomMtrrPair (SystemParameter.PhysicalA= ddressBits, GenerateRandomCacheType (), &VariableMtrr[Index], NULL); >
    > +    AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index &= lt;< 1), VariableMtrr[Index].Base);
    >
    > +    AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index &= lt;< 1), VariableMtrr[Index].Mask);
    >
    > +  }
    >
    > +  Result =3D MtrrGetAllMtrrs (&Mtrrs);
    >
    > +  UT_ASSERT_EQUAL (Result, &Mtrrs);
    >
    > +  UT_ASSERT_MEM_EQUAL (Mtrrs.Variables.Mtrr, VariableMtrr, size= of (MTRR_VARIABLE_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_MTRR
    >
    > +  //
    >
    > +  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     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestMtrrSetAllMtrrs (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_SETTINGS        =            *Result;
    >
    > +  MTRR_SETTINGS        =            Mtrrs;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    Index;
    >
    > +  MSR_IA32_MTRR_DEF_TYPE_REGISTER Default;
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER      = SystemParameter;
    >
    > +  MTRR_LIB_TEST_CONTEXT      &nbs= p;    *LocalContext;
    >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +  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.VariableMtrrCoun= t; Index++) {
    >
    > +    GenerateRandomMtrrPair (SystemParameter.PhysicalA= ddressBits, GenerateRandomCacheType (), &Mtrrs.Variables.Mtrr[Index], N= ULL);
    >
    > +  }
    >
    > +  Result =3D MtrrSetAllMtrrs (&Mtrrs);
    >
    > +  UT_ASSERT_EQUAL (Result, &Mtrrs);
    >
    > +
    >
    > +  UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE), Mtrrs= .MtrrDefType);
    >
    > +  for (Index =3D 0; Index < SystemParameter.VariableMtrrCoun= t; Index++) {
    >
    > +    UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_PHYS= BASE0 + (Index << 1)), Mtrrs.Variables.Mtrr[Index].Base);
    >
    > +    UT_ASSERT_EQUAL (AsmReadMsr64 (MSR_IA32_MTRR_PHYS= MASK0 + (Index << 1)), Mtrrs.Variables.Mtrr[Index].Mask);
    >
    > +  }
    >
    > +
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Unit test of MtrrLib service MtrrGetMemoryAttributeInVariable= Mtrr()
    >
    > +
    >
    > +  @param[in]  Context    Ignored
    >
    > +
    >
    > +  @retval  UNIT_TEST_PASSED     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestMtrrGetMemoryAttributeInVariableMtrr (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_LIB_TEST_CONTEXT      &nbs= p;    *LocalContext;
    >
    > +  MTRR_LIB_SYSTEM_PARAMETER      = SystemParameter;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    Result;
    >
    > +  MTRR_VARIABLE_SETTING      &nbs= p;    VariableSetting[MTRR_NUMBER_OF_VARIABLE_MTRR];
    >
    > +  VARIABLE_MTRR        =            VariableMtrr[M= TRR_NUMBER_OF_VARIABLE_MTRR];
    >
    > +  UINT64         &= nbsp;           &nbs= p;    ValidMtrrBitsMask;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    ValidMtrrAddressMask;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    Index;
    >
    > +  MSR_IA32_MTRR_PHYSBASE_REGISTER Base;
    >
    > +  MSR_IA32_MTRR_PHYSMASK_REGISTER Mask;
    >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_TEST_CONTEXT *) Context;
    >
    > +
    >
    > +  CopyMem (&SystemParameter, LocalContext->SystemParamet= er, sizeof (SystemParameter));
    >
    > +
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +
    >
    > +  ValidMtrrBitsMask    =3D (1ull << System= Parameter.PhysicalAddressBits) - 1;
    >
    > +  ValidMtrrAddressMask =3D ValidMtrrBitsMask & 0xffffffffff= fff000ULL;
    >
    > +
    >
    > +  for (Index =3D 0; Index < SystemParameter.VariableMtrrCoun= t; Index++) {
    >
    > +    GenerateRandomMtrrPair (SystemParameter.PhysicalA= ddressBits, GenerateRandomCacheType (), &VariableSetting[Index], NULL);=
    >
    > +    AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0 + (Index &= lt;< 1), VariableSetting[Index].Base);
    >
    > +    AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0 + (Index &= lt;< 1), VariableSetting[Index].Mask);
    >
    > +  }
    >
    > +  Result =3D MtrrGetMemoryAttributeInVariableMtrr (ValidMtrrBit= sMask, ValidMtrrAddressMask, VariableMtrr);
    >
    > +  UT_ASSERT_EQUAL (Result, SystemParameter.VariableMtrrCount);<= br> >
    > +
    >
    > +  for (Index =3D 0; Index < SystemParameter.VariableMtrrCoun= t; Index++) {
    >
    > +    Base.Uint64    =3D VariableMtrr[In= dex].BaseAddress;
    >
    > +    Base.Bits.Type =3D (UINT32) VariableMtrr[Index].T= ype;
    >
    > +    UT_ASSERT_EQUAL (Base.Uint64, VariableSetting[Ind= ex].Base);
    >
    > +
    >
    > +    Mask.Uint64    =3D ~(VariableMtrr[= Index].Length - 1) & ValidMtrrBitsMask;
    >
    > +    Mask.Bits.V    =3D 1;
    >
    > +    UT_ASSERT_EQUAL (Mask.Uint64, VariableSetting[Ind= ex].Mask);
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // Negative test case when MTRRs are not supported
    >
    > +  //
    >
    > +  SystemParameter.MtrrSupported =3D FALSE;
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +  Result =3D MtrrGetMemoryAttributeInVariableMtrr (ValidMtrrBit= sMask, ValidMtrrAddressMask, VariableMtrr);
    >
    > +  UT_ASSERT_EQUAL (Result, 0);
    >
    > +
    >
    > +  //
    >
    > +  // Expect ASSERT() if variable MTRR count is > MTRR_NUMBER= _OF_VARIABLE_MTRR
    >
    > +  //
    >
    > +  SystemParameter.MtrrSupported =3D TRUE;
    >
    > +  SystemParameter.VariableMtrrCount =3D MTRR_NUMBER_OF_VARIABLE= _MTRR + 1;
    >
    > +  InitializeMtrrRegs (&SystemParameter);
    >
    > +  UT_EXPECT_ASSERT_FAILURE (MtrrGetMemoryAttributeInVariableMtr= r (ValidMtrrBitsMask, ValidMtrrAddressMask, VariableMtrr), NULL);
    >
    > +
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Unit test of MtrrLib service MtrrDebugPrintAllMtrrs()
    >
    > +
    >
    > +  @param[in]  Context    Ignored
    >
    > +
    >
    > +  @retval  UNIT_TEST_PASSED     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion 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     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestMtrrGetDefaultMemoryType (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_LIB_TEST_CONTEXT     *LocalContext;<= br> >
    > +  UINTN         &n= bsp;           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->SystemParamet= er, sizeof (SystemParameter));
    >
    > +  //
    >
    > +  // 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[In= dex];
    >
    > +    InitializeMtrrRegs (&SystemParameter);
    >
    > +    Result =3D MtrrGetDefaultMemoryType ();
    >
    > +    UT_ASSERT_EQUAL (Result, SystemParameter.DefaultC= acheType);
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // If MTRRs are not supported, then always return CacheUncach= eable
    >
    > +  //
    >
    > +  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 MtrrSetMemoryAttributeInMtrrSett= ings().
    >
    > +
    >
    > +  @param[in]  Context    Ignored
    >
    > +
    >
    > +  @retval  UNIT_TEST_PASSED     &= nbsp;       The Unit test has completed and t= he test
    >
    > +           &n= bsp;            = ;            &n= bsp;   case was successful.
    >
    > +  @retval  UNIT_TEST_ERROR_TEST_FAILED  A test case a= ssertion has failed.
    >
    > +
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestMtrrSetMemoryAttributeInMtrrSettings (
    >
    > +  IN UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  CONST MTRR_LIB_SYSTEM_PARAMETER *SystemParameter;
    >
    > +  RETURN_STATUS        =            Status;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    UcCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WtCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WbCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WpCount;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    WcCount;
    >
    > +
    >
    > +  UINTN         &n= bsp;            = ;     MtrrIndex;
    >
    > +  UINTN         &n= bsp;            = ;     Index;
    >
    > +  MTRR_SETTINGS        =            LocalMtrrs; >
    > +
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       RawMtrrRange[MTRR_NUMBER_OF_VARIAB= LE_MTRR];
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       ExpectedMemoryRanges[MTRR_NUMBER_O= F_FIXED_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1];
    >
    > +  UINT32         &= nbsp;           &nbs= p;    ExpectedVariableMtrrUsage;
    >
    > +  UINTN         &n= bsp;            = ;     ExpectedMemoryRangesCount;
    >
    > +
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;       ActualMemoryRanges[MTRR_NUMBER_OF_= FIXED_MTRR * sizeof (UINT64) + 2 * MTRR_NUMBER_OF_VARIABLE_MTRR + 1];
    >
    > +  UINT32         &= nbsp;           &nbs= p;    ActualVariableMtrrUsage;
    >
    > +  UINTN         &n= bsp;            = ;     ActualMemoryRangesCount;
    >
    > +
    >
    > +  MTRR_SETTINGS        =            *Mtrrs[2];
    >
    > +
    >
    > +  SystemParameter =3D (MTRR_LIB_SYSTEM_PARAMETER *) Context; >
    > +  GenerateRandomMemoryTypeCombination (
    >
    > +    SystemParameter->VariableMtrrCount - PatchPcdG= et32 (PcdCpuNumberOfReservedVariableMtrrs),
    >
    > +    &UcCount, &WtCount, &WbCount, &Wp= Count, &WcCount
    >
    > +    );
    >
    > +  GenerateValidAndConfigurableMtrrPairs (
    >
    > +    SystemParameter->PhysicalAddressBits, RawMtrrR= ange,
    >
    > +    UcCount, WtCount, WbCount, WpCount, WcCount
    >
    > +    );
    >
    > +
    >
    > +  ExpectedVariableMtrrUsage =3D UcCount + WtCount + WbCount + W= pCount + WcCount;
    >
    > +  ExpectedMemoryRangesCount =3D ARRAY_SIZE (ExpectedMemoryRange= s);
    >
    > +  GetEffectiveMemoryRanges (
    >
    > +    SystemParameter->DefaultCacheType,
    >
    > +    SystemParameter->PhysicalAddressBits,
    >
    > +    RawMtrrRange, ExpectedVariableMtrrUsage,
    >
    > +    ExpectedMemoryRanges, &ExpectedMemoryRangesCo= unt
    >
    > +    );
    >
    > +
    >
    > +  UT_LOG_INFO ("--- Expected Memory Ranges [%d] ---\n"= ;, ExpectedMemoryRangesCount);
    >
    > +  DumpMemoryRanges (ExpectedMemoryRanges, ExpectedMemoryRangesC= ount);
    >
    > +  //
    >
    > +  // 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); Mtrr= Index++) {
    >
    > +    for (Index =3D 0; Index < ExpectedMemoryRanges= Count; Index++) {
    >
    > +      Status =3D MtrrSetMemoryAttributeInMt= rrSettings (
    >
    > +           &n= bsp;     Mtrrs[MtrrIndex],
    >
    > +           &n= bsp;     ExpectedMemoryRanges[Index].BaseAddress,
    >
    > +           &n= bsp;     ExpectedMemoryRanges[Index].Length,
    >
    > +           &n= bsp;     ExpectedMemoryRanges[Index].Type
    >
    > +           &n= bsp;     );
    >
    > +      UT_ASSERT_TRUE (Status =3D=3D RETURN_= SUCCESS || Status =3D=3D RETURN_OUT_OF_RESOURCES || Status =3D=3D RETURN_BU= FFER_TOO_SMALL);
    >
    > +      if (Status =3D=3D RETURN_OUT_OF_RESOU= RCES || Status =3D=3D RETURN_BUFFER_TOO_SMALL) {
    >
    > +        return UNIT_TEST_SKIPPED;=
    >
    > +      }
    >
    > +    }
    >
    > +
    >
    > +    if (Mtrrs[MtrrIndex] =3D=3D NULL) {
    >
    > +      ZeroMem (&LocalMtrrs, sizeof (Loc= alMtrrs));
    >
    > +      MtrrGetAllMtrrs (&LocalMtrrs); >
    > +    }
    >
    > +    ActualMemoryRangesCount =3D ARRAY_SIZE (ActualMem= oryRanges);
    >
    > +    CollectTestResult (
    >
    > +      SystemParameter->DefaultCacheType,= SystemParameter->PhysicalAddressBits, SystemParameter->VariableMtrrC= ount,
    >
    > +      &LocalMtrrs, ActualMemoryRanges, = &ActualMemoryRangesCount, &ActualVariableMtrrUsage
    >
    > +      );
    >
    > +    UT_LOG_INFO ("--- Actual Memory Ranges [%d] = ---\n", ActualMemoryRangesCount);
    >
    > +    DumpMemoryRanges (ActualMemoryRanges, ActualMemor= yRangesCount);
    >
    > +    VerifyMemoryRanges (ExpectedMemoryRanges, Expecte= dMemoryRangesCount, ActualMemoryRanges, 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 PcdCp= uNumberOfReservedVariableMtrrs.
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +SavePcdValue (
    >
    > +  UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT  *Loca= lContext;
    >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_C= ONTEXT *) Context;
    >
    > +  LocalContext->NumberOfReservedVariableMtrrs =3D PatchPcdGe= t32 (PcdCpuNumberOfReservedVariableMtrrs);
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Clean up routine for UnitTestGetFirmwareVariableMtrrCount().<= br> >
    > +
    >
    > +  @param Context  Point to a UINT32 data to save the PcdCp= uNumberOfReservedVariableMtrrs.
    >
    > +**/
    >
    > +VOID
    >
    > +EFIAPI
    >
    > +RestorePcdValue (
    >
    > +  UNIT_TEST_CONTEXT  Context
    >
    > +  )
    >
    > +{
    >
    > +  MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT  *Loca= lContext;
    >
    > +
    >
    > +  LocalContext =3D (MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_C= ONTEXT *) Context;
    >
    > +  PatchPcdSet32 (PcdCpuNumberOfReservedVariableMtrrs, LocalCont= ext->NumberOfReservedVariableMtrrs);
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Initialize the unit test framework, suite, and unit tests for= the
    >
    > +  ResetSystemLib and run the ResetSystemLib unit test.
    >
    > +
    >
    > +  @param Iteration       &nb= sp;       Iteration of testing MtrrSetMemoryA= ttributeInMtrrSettings
    >
    > +           &n= bsp;            = ;         and MtrrSetMemoryAttribut= esInMtrrSettings using random inputs.
    >
    > +
    >
    > +  @retval  EFI_SUCCESS      =      All test cases were dispatched.
    >
    > +  @retval  EFI_OUT_OF_RESOURCES  There are not enough= resources available to
    >
    > +           &n= bsp;            = ;         initialize the unit tests= .
    >
    > +**/
    >
    > +STATIC
    >
    > +EFI_STATUS
    >
    > +EFIAPI
    >
    > +UnitTestingEntry (
    >
    > +  UINTN         &n= bsp;            = ; Iteration
    >
    > +  )
    >
    > +{
    >
    > +  EFI_STATUS        &nb= sp;            =             &nb= sp;      Status;
    >
    > +  UNIT_TEST_FRAMEWORK_HANDLE      = ;            &n= bsp;     Framework;
    >
    > +  UNIT_TEST_SUITE_HANDLE      &nb= sp;            =          MtrrApiTests;
    >
    > +  UINTN         &n= bsp;            = ;            &n= bsp;          Index;
    >
    > +  UINTN         &n= bsp;            = ;            &n= bsp;          SystemIndex;
    >
    > +  MTRR_LIB_TEST_CONTEXT      &nbs= p;            &= nbsp;         Context;
    >
    > +  MTRR_LIB_GET_FIRMWARE_VARIABLE_MTRR_COUNT_CONTEXT GetFirmware= VariableMtrrCountContext;
    >
    > +
    >
    > +  Context.SystemParameter      &n= bsp;            = ;          =3D &mDefaultSy= stemParameter;
    >
    > +  GetFirmwareVariableMtrrCountContext.SystemParameter =3D &= mDefaultSystemParameter;
    >
    > +  Framework =3D NULL;
    >
    > +
    >
    > +  DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME,= UNIT_TEST_APP_VERSION));
    >
    > +
    >
    > +  //
    >
    > +  // Setup the test framework for running the tests.
    >
    > +  //
    >
    > +  Status =3D InitUnitTestFramework (&Framework, UNIT_TEST_A= PP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION);
    >
    > +  if (EFI_ERROR (Status)) {
    >
    > +    DEBUG ((DEBUG_ERROR, "Failed in InitUnitTest= Framework. Status =3D %r\n", Status));
    >
    > +    goto EXIT;
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // --------------Suite-----------Description--------------Nam= e----------Function--------Pre---Post-------------------Context-----------<= br> >
    > +  //
    >
    > +
    >
    > +  //
    >
    > +  // Populate the MtrrLib API Unit Test Suite.
    >
    > +  //
    >
    > +  Status =3D CreateUnitTestSuite (&MtrrApiTests, Framework,= "MtrrLib API Tests", "MtrrLib.MtrrLib", NULL, NULL); >
    > +  if (EFI_ERROR (Status)) {
    >
    > +    DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTe= stSuite for MtrrLib API Tests\n"));
    >
    > +    Status =3D EFI_OUT_OF_RESOURCES;
    >
    > +    goto EXIT;
    >
    > +  }
    >
    > +  AddTestCase (MtrrApiTests, "Test IsMtrrSupported",&= nbsp;           &nbs= p;         "MtrrSupported"= ;,            &= nbsp;           UnitTestI= sMtrrSupported,          =             NULL, NU= LL, &Context);
    >
    > +  AddTestCase (MtrrApiTests, "Test GetVariableMtrrCount&qu= ot;,            = ;     "GetVariableMtrrCount",  &nbs= p;            &= nbsp; UnitTestGetVariableMtrrCount,      &nbs= p;          NULL, NULL, &C= ontext);
    >
    > +  AddTestCase (MtrrApiTests, "Test GetFirmwareVariableMtrr= Count",         "GetFirmw= areVariableMtrrCount",        = UnitTestGetFirmwareVariableMtrrCount,      &= nbsp;  SavePcdValue, RestorePcdValue, &GetFirmwareVariableMtrrCoun= tContext);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrGetMemoryAttribute&= quot;,           &nb= sp;   "MtrrGetMemoryAttribute",    =            UnitTestMtrrGe= tMemoryAttribute,         &nbs= p;     NULL, NULL, &Context);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrGetFixedMtrr",=             &nb= sp;        "MtrrGetFixedMtrr",=             &nb= sp;        UnitTestMtrrGetFixedMtrr,&nbs= p;            &= nbsp;       NULL, NULL, &Context);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrGetAllMtrrs",&= nbsp;           &nbs= p;         "MtrrGetAllMtrrs&qu= ot;,            = ;          UnitTestMtrrGetAllM= trrs,           &nbs= p;          NULL, NULL, &C= ontext);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrSetAllMtrrs",&= nbsp;           &nbs= p;         "MtrrSetAllMtrrs&qu= ot;,            = ;          UnitTestMtrrSetAllM= trrs,           &nbs= p;          NULL, NULL, &C= ontext);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrGetMemoryAttributeI= nVariableMtrr", "MtrrGetMemoryAttributeInVariableMtrr", Unit= TestMtrrGetMemoryAttributeInVariableMtrr, NULL, NULL, &Context);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrDebugPrintAllMtrrs&= quot;,           &nb= sp;   "MtrrDebugPrintAllMtrrs",    =            UnitTestMtrrDe= bugPrintAllMtrrs,         &nbs= p;     NULL, NULL, &Context);
    >
    > +  AddTestCase (MtrrApiTests, "Test MtrrGetDefaultMemoryTyp= e",           &= nbsp; "MtrrGetDefaultMemoryType",     &n= bsp;       UnitTestMtrrGetDefaultMemoryType,&= nbsp;            NUL= L, NULL, &Context);
    >
    > +
    >
    > +  for (SystemIndex =3D 0; SystemIndex < ARRAY_SIZE (mSystemP= arameters); SystemIndex++) {
    >
    > +    for (Index =3D 0; Index < Iteration; Index++) = {
    >
    > +      AddTestCase (MtrrApiTests, "Test= InvalidMemoryLayouts",        = ;          "InvalidMemory= Layouts",          &= nbsp;       UnitTestInvalidMemoryLayouts,&nbs= p;            &= nbsp;    InitializeSystem, NULL, &mSystemParameters[Syst= emIndex]);
    >
    > +      AddTestCase (MtrrApiTests, "Test= MtrrSetMemoryAttributeInMtrrSettings",  "MtrrSetMemoryAttri= buteInMtrrSettings",  UnitTestMtrrSetMemoryAttributeInMtrrSetting= s,  InitializeSystem, NULL, &mSystemParameters[SystemIndex]);
    >
    > +      AddTestCase (MtrrApiTests, "Test= MtrrSetMemoryAttributesInMtrrSettings", "MtrrSetMemoryAttributes= InMtrrSettings", UnitTestMtrrSetMemoryAttributesInMtrrSettings, Initia= lizeSystem, 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 executi= on.
    >
    > +
    >
    > +  @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/= UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h
    > new file mode 100644
    > index 0000000000..9750523133
    > --- /dev/null
    > +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/MtrrLibUnitTest.h
    > @@ -0,0 +1,182 @@
    > +/** @file
    >
    > +
    >
    > +  Copyright (c) 2020, Intel Corporation. All rights reserved.&l= t;BR>
    >
    > +  SPDX-License-Identifier: BSD-2-Clause-Patent
    >
    > +
    >
    > +**/
    >
    > +
    >
    > +#ifndef _MTRR_SUPPORT_H_
    >
    > +#define _MTRR_SUPPORT_H_
    >
    > +
    >
    > +#include <stdio.h>
    >
    > +#include <stdlib.h>
    >
    > +#include <string.h>
    >
    > +#include <stdarg.h>
    >
    > +#include <stddef.h>
    >
    > +#include <setjmp.h>
    >
    > +#include <cmocka.h>
    >
    > +#include <time.h>
    >
    > +
    >
    > +#include <Uefi.h>
    >
    > +#include <Library/BaseLib.h>
    >
    > +#include <Library/BaseMemoryLib.h>
    >
    > +#include <Library/DebugLib.h>
    >
    > +#include <Library/UnitTestLib.h>
    >
    > +#include <Library/MtrrLib.h>
    >
    > +#include <Library/UnitTestHostBaseLib.h>
    >
    > +
    >
    > +#include <Register/ArchitecturalMsr.h>
    >
    > +#include <Register/Cpuid.h>
    >
    > +#include <Register/Msr.h>
    >
    > +
    >
    > +#define UNIT_TEST_APP_NAME       = "MtrrLib Unit Tests"
    >
    > +#define UNIT_TEST_APP_VERSION     "1.0"= ;
    >
    > +
    >
    > +#define SCRATCH_BUFFER_SIZE       SIZE= _16KB
    >
    > +
    >
    > +typedef struct {
    >
    > +  UINT8         &n= bsp;        PhysicalAddressBits;
    >
    > +  BOOLEAN         =        MtrrSupported;
    >
    > +  BOOLEAN         =        FixedMtrrSupported;
    >
    > +  MTRR_MEMORY_CACHE_TYPE DefaultCacheType;
    >
    > +  UINT32         &= nbsp;       VariableMtrrCount;
    >
    > +} MTRR_LIB_SYSTEM_PARAMETER;
    >
    > +
    >
    > +extern UINT32         &= nbsp;           &nbs= p;     mFixedMtrrsIndex[];
    >
    > +
    >
    > +/**
    >
    > +  Initialize the MTRR registers.
    >
    > +
    >
    > +  @param SystemParameter System parameter that controls the MTR= R registers initialization.
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +InitializeMtrrRegs (
    >
    > +  IN MTRR_LIB_SYSTEM_PARAMETER  *SystemParameter
    >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  Initialize the MTRR registers.
    >
    > +
    >
    > +  @param Context System parameter that controls the MTRR regist= ers initialization.
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +InitializeSystem (
    >
    > +  IN UNIT_TEST_CONTEXT       = ; Context
    >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  Return a random memory cache type.
    >
    > +**/
    >
    > +MTRR_MEMORY_CACHE_TYPE
    >
    > +GenerateRandomCacheType (
    >
    > +  VOID
    >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  Generate random MTRRs.
    >
    > +
    >
    > +  @param PhysicalAddressBits  Physical address bits.
    >
    > +  @param RawMemoryRanges      Return t= he 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    &nbs= p;            &= nbsp;  PhysicalAddressBits,
    >
    > +  IN OUT MTRR_MEMORY_RANGE      &= nbsp;  *RawMemoryRanges,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  UcCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WtCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WbCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WpCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WcCount
    >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  Convert the MTRR BASE/MASK array to memory ranges.
    >
    > +
    >
    > +  @param DefaultType       &= nbsp;  Default memory type.
    >
    > +  @param PhysicalAddressBits  Physical address bits.
    >
    > +  @param RawMemoryRanges      Raw memo= ry ranges.
    >
    > +  @param RawMemoryRangeCount  Count of raw memory ranges.<= br> >
    > +  @param MemoryRanges       =   Memory ranges.
    >
    > +  @param MemoryRangeCount     Count of memo= ry ranges.
    >
    > +**/
    >
    > +VOID
    >
    > +GetEffectiveMemoryRanges (
    >
    > +  IN MTRR_MEMORY_CACHE_TYPE DefaultType,
    >
    > +  IN UINT32        &nbs= p;        PhysicalAddressBits,
    >
    > +  IN MTRR_MEMORY_RANGE      *RawMemory= Ranges,
    >
    > +  IN UINT32        &nbs= p;        RawMemoryRangeCount,
    >
    > +  OUT MTRR_MEMORY_RANGE     *MemoryRanges,<= br> >
    > +  OUT UINTN        &nbs= p;        *MemoryRangeCount
    >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  Generate random MTRR BASE/MASK for a specified type.
    >
    > +
    >
    > +  @param PhysicalAddressBits Physical address bits.
    >
    > +  @param CacheType       &nb= sp;   Cache type.
    >
    > +  @param MtrrPair       &nbs= p;    Return the random MTRR.
    >
    > +  @param MtrrMemoryRange     Return the ran= dom memory range.
    >
    > +**/
    >
    > +VOID
    >
    > +GenerateRandomMtrrPair (
    >
    > +  IN  UINT32       &nbs= p;         PhysicalAddressBits,
    >
    > +  IN  MTRR_MEMORY_CACHE_TYPE CacheType,
    >
    > +  OUT MTRR_VARIABLE_SETTING  *MtrrPair,   &= nbsp;   OPTIONAL
    >
    > +  OUT MTRR_MEMORY_RANGE      *MtrrMemo= ryRange OPTIONAL
    >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  Collect the test result.
    >
    > +
    >
    > +  @param DefaultType       &= nbsp;  Default memory type.
    >
    > +  @param PhysicalAddressBits  Physical address bits.
    >
    > +  @param VariableMtrrCount    Count of variable = MTRRs.
    >
    > +  @param Mtrrs        &= nbsp;       MTRR settings to collect from. >
    > +  @param Ranges        =        Return the memory ranges.
    >
    > +  @param RangeCount       &n= bsp;   Return the count of memory ranges.
    >
    > +  @param MtrrCount       &nb= sp;    Return the count of variable MTRRs being used.
    >
    > +**/
    >
    > +VOID
    >
    > +CollectTestResult (
    >
    > +  IN     MTRR_MEMORY_CACHE_TYPE DefaultType= ,
    >
    > +  IN     UINT32    &nbs= p;            Physic= alAddressBits,
    >
    > +  IN     UINT32    &nbs= p;            Variab= leMtrrCount,
    >
    > +  IN     MTRR_SETTINGS   &nb= sp;      *Mtrrs,
    >
    > +  OUT    MTRR_MEMORY_RANGE   &nbs= p;  *Ranges,
    >
    > +  IN OUT UINTN        &= nbsp;         *RangeCount,
    >
    > +  OUT    UINT32     &nb= sp;           *MtrrCount<= br> >
    > +  );
    >
    > +
    >
    > +/**
    >
    > +  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.<BR&= gt;
    >
    > +# SPDX-License-Identifier: BSD-2-Clause-Patent
    >
    > +##
    >
    > +
    >
    > +[Defines]
    >
    > +  INF_VERSION        &n= bsp;           =3D 0x0001= 0006
    >
    > +  BASE_NAME        &nbs= p;             = = =3D MtrrLibUnitTestHost
    >
    > +  FILE_GUID        &nbs= p;             = = =3D A1542D84-B64D-4847-885E-0509084376AB
    >
    > +  MODULE_TYPE        &n= bsp;           =3D HOST_A= PPLICATION
    >
    > +  VERSION_STRING        = ;         =3D 1.0
    >
    > +
    >
    > +#
    >
    > +# The following information is for reference only and not required b= y 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=    ## SOMETIMES_CONSUMES
    >
    > diff --git a/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c b/UefiCpuP= kg/Library/MtrrLib/UnitTest/Support.c
    > new file mode 100644
    > index 0000000000..a7eed45940
    > --- /dev/null
    > +++ b/UefiCpuPkg/Library/MtrrLib/UnitTest/Support.c
    > @@ -0,0 +1,923 @@
    > +/** @file
    >
    > +  Unit tests of the MtrrLib instance of the MtrrLib class
    >
    > +
    >
    > +  Copyright (c) 2018 - 2020, Intel Corporation. All rights rese= rved.<BR>
    >
    > +  SPDX-License-Identifier: BSD-2-Clause-Patent
    >
    > +
    >
    > +**/
    >
    > +
    >
    > +#include "MtrrLibUnitTest.h"
    >
    > +
    >
    > +MTRR_MEMORY_CACHE_TYPE mMemoryCacheTypes[] =3D {
    >
    > +  CacheUncacheable, CacheWriteCombining, CacheWriteThrough, Cac= heWriteProtected, CacheWriteBack
    >
    > +  };
    >
    > +
    >
    > +UINT64          &n= bsp;            = ;    mFixedMtrrsValue[MTRR_NUMBER_OF_FIXED_MTRR];
    >
    > +MSR_IA32_MTRR_PHYSBASE_REGISTER  mVariableMtrrsPhysBase[MTRR_NU= MBER_OF_VARIABLE_MTRR];
    >
    > +MSR_IA32_MTRR_PHYSMASK_REGISTER  mVariableMtrrsPhysMask[MTRR_NU= MBER_OF_VARIABLE_MTRR];
    >
    > +MSR_IA32_MTRR_DEF_TYPE_REGISTER  mDefTypeMsr;
    >
    > +MSR_IA32_MTRRCAP_REGISTER        = mMtrrCapMsr;
    >
    > +CPUID_VERSION_INFO_EDX       &nbs= p;   mCpuidVersionInfoEdx;
    >
    > +CPUID_VIR_PHY_ADDRESS_SIZE_EAX   mCpuidVirPhyAddressSizeEa= x;
    >
    > +
    >
    > +/**
    >
    > +  Retrieves CPUID information.
    >
    > +
    >
    > +  Executes the CPUID instruction with EAX set to the value spec= ified by Index.
    >
    > +  This function always returns Index.
    >
    > +  If Eax is not NULL, then the value of EAX after CPUID is retu= rned in Eax.
    >
    > +  If Ebx is not NULL, then the value of EBX after CPUID is retu= rned in Ebx.
    >
    > +  If Ecx is not NULL, then the value of ECX after CPUID is retu= rned in Ecx.
    >
    > +  If Edx is not NULL, then the value of EDX after CPUID is retu= rned 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
    >
    > +           &n= bsp;    instruction.
    >
    > +  @param  Eax   The pointer to the 32-bit EAX va= lue returned by the CPUID
    >
    > +           &n= bsp;    instruction. This is an optional parameter that may = be NULL.
    >
    > +  @param  Ebx   The pointer to the 32-bit EBX va= lue returned by the CPUID
    >
    > +           &n= bsp;    instruction. This is an optional parameter that may = be NULL.
    >
    > +  @param  Ecx   The pointer to the 32-bit ECX va= lue returned by the CPUID
    >
    > +           &n= bsp;    instruction. This is an optional parameter that may = be NULL.
    >
    > +  @param  Edx   The pointer to the 32-bit EDX va= lue returned by the CPUID
    >
    > +           &n= bsp;    instruction. This is an optional parameter that may = be NULL.
    >
    > +
    >
    > +  @return Index.
    >
    > +
    >
    > +**/
    >
    > +UINT32
    >
    > +EFIAPI
    >
    > +UnitTestMtrrLibAsmCpuid (
    >
    > +  IN      UINT32   &nbs= p;            &= nbsp;   Index,
    >
    > +  OUT     UINT32    &nb= sp;            =    *Eax,  OPTIONAL
    >
    > +  OUT     UINT32    &nb= sp;            =    *Ebx,  OPTIONAL
    >
    > +  OUT     UINT32    &nb= sp;            =    *Ecx,  OPTIONAL
    >
    > +  OUT     UINT32    &nb= sp;            =    *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;<= br> >
    > +    }
    >
    > +    return Index;
    >
    > +    break;
    >
    > +  case CPUID_VIR_PHY_ADDRESS_SIZE:
    >
    > +    if (Eax !=3D NULL) {
    >
    > +      *Eax =3D mCpuidVirPhyAddressSizeEax.U= int32;
    >
    > +    }
    >
    > +    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 param= eter checking is
    >
    > +  performed on Index, and some Index values may cause CPU excep= tions. The
    >
    > +  caller must either guarantee that Index is valid, or the call= er must set up
    >
    > +  exception handlers to catch the exceptions. This function is = only available
    >
    > +  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); I= ndex++) {
    >
    > +    if (MsrIndex =3D=3D mFixedMtrrsIndex[Index]) { >
    > +      return mFixedMtrrsValue[Index];
    >
    > +    }
    >
    > +  }
    >
    > +
    >
    > +  if ((MsrIndex >=3D MSR_IA32_MTRR_PHYSBASE0) &&
    >
    > +      (MsrIndex <=3D MSR_IA32_MTRR_PHYSM= ASK0 + (MTRR_NUMBER_OF_VARIABLE_MTRR << 1))) {
    >
    > +    if (MsrIndex % 2 =3D=3D 0) {
    >
    > +      Index =3D (MsrIndex - MSR_IA32_MTRR_P= HYSBASE0) >> 1;
    >
    > +      return mVariableMtrrsPhysBase[Index].= Uint64;
    >
    > +    } else {
    >
    > +      Index =3D (MsrIndex - MSR_IA32_MTRR_P= HYSMASK0) >> 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), an= d returns the
    >
    > +  value.
    >
    > +
    >
    > +  Writes the 64-bit value specified by Value to the MSR specifi= ed by Index. The
    >
    > +  64-bit value written to the MSR is returned. No parameter che= cking 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 caller
    >
    > +  must establish proper exception handlers. This function is on= ly available 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   &nbs= p;            &= nbsp;   MsrIndex,
    >
    > +  IN      UINT64   &nbs= p;            &= nbsp;   Value
    >
    > +  )
    >
    > +{
    >
    > +  UINT32 Index;
    >
    > +
    >
    > +  for (Index =3D 0; Index < ARRAY_SIZE (mFixedMtrrsValue); I= ndex++) {
    >
    > +    if (MsrIndex =3D=3D mFixedMtrrsIndex[Index]) { >
    > +      mFixedMtrrsValue[Index] =3D Value; >
    > +      return Value;
    >
    > +    }
    >
    > +  }
    >
    > +
    >
    > +  if ((MsrIndex >=3D MSR_IA32_MTRR_PHYSBASE0) &&
    >
    > +      (MsrIndex <=3D MSR_IA32_MTRR_PHYSM= ASK0 + (MTRR_NUMBER_OF_VARIABLE_MTRR << 1))) {
    >
    > +    if (MsrIndex % 2 =3D=3D 0) {
    >
    > +      Index =3D (MsrIndex - MSR_IA32_MTRR_P= HYSBASE0) >> 1;
    >
    > +      mVariableMtrrsPhysBase[Index].Uint64 = = =3D Value;
    >
    > +      return Value;
    >
    > +    } else {
    >
    > +      Index =3D (MsrIndex - MSR_IA32_MTRR_P= HYSMASK0) >> 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 the MTRR registers.
    >
    > +
    >
    > +  @param SystemParameter System parameter that controls the MTR= R registers initialization.
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +InitializeMtrrRegs (
    >
    > +  IN MTRR_LIB_SYSTEM_PARAMETER  *SystemParameter
    >
    > +  )
    >
    > +{
    >
    > +  UINT32         &= nbsp;          Index;
    >
    > +
    >
    > +  SetMem (mFixedMtrrsValue, sizeof (mFixedMtrrsValue), SystemPa= rameter->DefaultCacheType);
    >
    > +
    >
    > +  for (Index =3D 0; Index < ARRAY_SIZE (mVariableMtrrsPhysBa= se); Index++) {
    >
    > +    mVariableMtrrsPhysBase[Index].Uint64  &= nbsp;      =3D 0;
    >
    > +    mVariableMtrrsPhysBase[Index].Bits.Type &nbs= p;    =3D SystemParameter->DefaultCacheType;
    >
    > +    mVariableMtrrsPhysBase[Index].Bits.Reserved1 =3D = 0;
    >
    > +
    >
    > +    mVariableMtrrsPhysMask[Index].Uint64  &= nbsp;      =3D 0;
    >
    > +    mVariableMtrrsPhysMask[Index].Bits.V  &= nbsp;      =3D 0;
    >
    > +    mVariableMtrrsPhysMask[Index].Bits.Reserved1 =3D = 0;
    >
    > +  }
    >
    > +
    >
    > +  mDefTypeMsr.Bits.E       &= nbsp; =3D 1;
    >
    > +  mDefTypeMsr.Bits.FE       = =3D 1;
    >
    > +  mDefTypeMsr.Bits.Type      =3D Syste= mParameter->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 Syste= mParameter->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     &= nbsp;           &nbs= p;    =3D SystemParameter->MtrrSupported;
    >
    > +  mCpuidVirPhyAddressSizeEax.Bits.PhysicalAddressBits =3D Syste= mParameter->PhysicalAddressBits;
    >
    > +
    >
    > +  //
    >
    > +  // Hook BaseLib functions used by MtrrLib that require some e= mulation.
    >
    > +  //
    >
    > +  gUnitTestHostBaseLib.X86->AsmCpuid    =   =3D UnitTestMtrrLibAsmCpuid;
    >
    > +  gUnitTestHostBaseLib.X86->AsmReadMsr64  =3D UnitTestM= trrLibAsmReadMsr64;
    >
    > +  gUnitTestHostBaseLib.X86->AsmWriteMsr64 =3D UnitTestMtrrLi= bAsmWriteMsr64;
    >
    > +
    >
    > +  return UNIT_TEST_PASSED;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Initialize the MTRR registers.
    >
    > +
    >
    > +  @param Context System parameter that controls the MTRR regist= ers initialization.
    >
    > +**/
    >
    > +UNIT_TEST_STATUS
    >
    > +EFIAPI
    >
    > +InitializeSystem (
    >
    > +  IN UNIT_TEST_CONTEXT       = ; Context
    >
    > +  )
    >
    > +{
    >
    > +  return InitializeMtrrRegs ((MTRR_LIB_SYSTEM_PARAMETER *) Cont= ext);
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Collect the test result.
    >
    > +
    >
    > +  @param DefaultType       &= nbsp;  Default memory type.
    >
    > +  @param PhysicalAddressBits  Physical address bits.
    >
    > +  @param VariableMtrrCount    Count of variable = MTRRs.
    >
    > +  @param Mtrrs        &= nbsp;       MTRR settings to collect from. >
    > +  @param Ranges        =        Return the memory ranges.
    >
    > +  @param RangeCount       &n= bsp;   Return the count of memory ranges.
    >
    > +  @param MtrrCount       &nb= sp;    Return the count of variable MTRRs being used.
    >
    > +**/
    >
    > +VOID
    >
    > +CollectTestResult (
    >
    > +  IN     MTRR_MEMORY_CACHE_TYPE DefaultType= ,
    >
    > +  IN     UINT32    &nbs= p;            Physic= alAddressBits,
    >
    > +  IN     UINT32    &nbs= p;            Variab= leMtrrCount,
    >
    > +  IN     MTRR_SETTINGS   &nb= sp;      *Mtrrs,
    >
    > +  OUT    MTRR_MEMORY_RANGE   &nbs= p;  *Ranges,
    >
    > +  IN OUT UINTN        &= nbsp;         *RangeCount,
    >
    > +  OUT    UINT32     &nb= sp;           *MtrrCount<= br> >
    > +  )
    >
    > +{
    >
    > +  UINTN         &n= bsp;   Index;
    >
    > +  UINT64         &= nbsp;  MtrrValidBitsMask;
    >
    > +  UINT64         &= nbsp;  MtrrValidAddressMask;
    >
    > +  MTRR_MEMORY_RANGE RawMemoryRanges[ARRAY_SIZE (Mtrrs->Varia= bles.Mtrr)];
    >
    > +
    >
    > +  ASSERT (Mtrrs !=3D NULL);
    >
    > +  ASSERT (VariableMtrrCount <=3D ARRAY_SIZE (Mtrrs->Varia= bles.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 *) &Mtr= rs->Variables.Mtrr[Index].Mask)->Bits.V =3D=3D 1) {
    >
    > +      RawMemoryRanges[*MtrrCount].BaseAddre= ss =3D Mtrrs->Variables.Mtrr[Index].Base & MtrrValidAddressMask;
    >
    > +      RawMemoryRanges[*MtrrCount].Type = ;       =3D
    >
    > +        ((MSR_IA32_MTRR_PHYSBASE_= REGISTER *) &Mtrrs->Variables.Mtrr[Index].Base)->Bits.Type;
    >
    > +      RawMemoryRanges[*MtrrCount].Length&nb= sp;     =3D
    >
    > +          ((~(Mtrrs->= ;Variables.Mtrr[Index].Mask & MtrrValidAddressMask)) & MtrrValidBit= sMask) + 1;
    >
    > +      (*MtrrCount)++;
    >
    > +    }
    >
    > +  }
    >
    > +
    >
    > +  GetEffectiveMemoryRanges (DefaultType, PhysicalAddressBits, R= awMemoryRanges, *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 - Sta= rt)) + Start;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  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 - Sta= rt)) + Start;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Generate random MTRR BASE/MASK for a specified type.
    >
    > +
    >
    > +  @param PhysicalAddressBits Physical address bits.
    >
    > +  @param CacheType       &nb= sp;   Cache type.
    >
    > +  @param MtrrPair       &nbs= p;    Return the random MTRR.
    >
    > +  @param MtrrMemoryRange     Return the ran= dom memory range.
    >
    > +**/
    >
    > +VOID
    >
    > +GenerateRandomMtrrPair (
    >
    > +  IN  UINT32       &nbs= p;         PhysicalAddressBits,
    >
    > +  IN  MTRR_MEMORY_CACHE_TYPE CacheType,
    >
    > +  OUT MTRR_VARIABLE_SETTING  *MtrrPair,   &= nbsp;   OPTIONAL
    >
    > +  OUT MTRR_MEMORY_RANGE      *MtrrMemo= ryRange OPTIONAL
    >
    > +  )
    >
    > +{
    >
    > +  MSR_IA32_MTRR_PHYSBASE_REGISTER PhysBase;
    >
    > +  MSR_IA32_MTRR_PHYSMASK_REGISTER PhysMask;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    SizeShift;
    >
    > +  UINT32         &= nbsp;           &nbs= p;    BaseShift;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    RandomBoundary;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    MaxPhysicalAddress;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    RangeSize;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    RangeBase;
    >
    > +  UINT64         &= nbsp;           &nbs= p;    PhysBasePhyMaskValidBitsMask;
    >
    > +
    >
    > +  MaxPhysicalAddress =3D 1ull << PhysicalAddressBits;
    >
    > +  do {
    >
    > +    SizeShift =3D Random32 (12, PhysicalAddressBits -= 1);
    >
    > +    RangeSize =3D 1ull << SizeShift;
    >
    > +
    >
    > +    BaseShift =3D Random32 (SizeShift, PhysicalAddres= sBits - 1);
    >
    > +    RandomBoundary =3D Random64 (0, 1ull << (Ph= ysicalAddressBits - BaseShift));
    >
    > +    RangeBase =3D RandomBoundary << BaseShift;<= br> >
    > +  } while (RangeBase < SIZE_1MB || RangeBase > MaxPhysica= lAddress - 1);
    >
    > +
    >
    > +  PhysBasePhyMaskValidBitsMask =3D (MaxPhysicalAddress - 1) &am= p; 0xfffffffffffff000ULL;
    >
    > +
    >
    > +  PhysBase.Uint64    =3D 0;
    >
    > +  PhysBase.Bits.Type =3D CacheType;
    >
    > +  PhysBase.Uint64   |=3D RangeBase & PhysBasePhyM= askValidBitsMask;
    >
    > +  PhysMask.Uint64    =3D 0;
    >
    > +  PhysMask.Bits.V    =3D 1;
    >
    > +  PhysMask.Uint64   |=3D ((~RangeSize) + 1) & Phy= sBasePhyMaskValidBitsMask;
    >
    > +
    >
    > +  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    &= nbsp;   =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->BaseAddress < Ranges[Count].BaseAd= dress + Ranges[Count].Length)) {
    >
    > +      return TRUE;
    >
    > +    }
    >
    > +  }
    >
    > +  return FALSE;
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Generate random MTRRs.
    >
    > +
    >
    > +  @param PhysicalAddressBits  Physical address bits.
    >
    > +  @param RawMemoryRanges      Return t= he 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    &nbs= p;            &= nbsp;  PhysicalAddressBits,
    >
    > +  IN OUT MTRR_MEMORY_RANGE      &= nbsp;  *RawMemoryRanges,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  UcCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WtCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WbCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WpCount,
    >
    > +  IN     UINT32    &nbs= p;            &= nbsp;  WcCount
    >
    > +  )
    >
    > +{
    >
    > +  UINT32         &= nbsp;           &nbs= p;    Index;
    >
    > +
    >
    > +  //
    >
    > +  // 1. Generate UC, WT, WB in order.
    >
    > +  //
    >
    > +  for (Index =3D 0; Index < UcCount; Index++) {
    >
    > +    GenerateRandomMtrrPair (PhysicalAddressBits, Cach= eUncacheable, NULL, &RawMemoryRanges[Index]);
    >
    > +  }
    >
    > +
    >
    > +  for (Index =3D UcCount; Index < UcCount + WtCount; Index++= ) {
    >
    > +    GenerateRandomMtrrPair (PhysicalAddressBits, Cach= eWriteThrough, NULL, &RawMemoryRanges[Index]);
    >
    > +  }
    >
    > +
    >
    > +  for (Index =3D UcCount + WtCount; Index < UcCount + WtCoun= t + WbCount; Index++) {
    >
    > +    GenerateRandomMtrrPair (PhysicalAddressBits, Cach= eWriteBack, NULL, &RawMemoryRanges[Index]);
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // 2. Generate WP MTRR and DO NOT overlap with WT, WB.
    >
    > +  //
    >
    > +  for (Index =3D UcCount + WtCount + WbCount; Index < UcCoun= t + WtCount + WbCount + WpCount; Index++) {
    >
    > +    GenerateRandomMtrrPair (PhysicalAddressBits, Cach= eWriteProtected, NULL, &RawMemoryRanges[Index]);
    >
    > +    while (RangesOverlap (&RawMemoryRanges[Index]= , &RawMemoryRanges[UcCount], WtCount + WbCount)) {
    >
    > +      GenerateRandomMtrrPair (PhysicalAddre= ssBits, CacheWriteProtected, NULL, &RawMemoryRanges[Index]);
    >
    > +    }
    >
    > +  }
    >
    > +
    >
    > +  //
    >
    > +  // 3. Generate WC MTRR and DO NOT overlap with WT, WB, WP. >
    > +  //
    >
    > +  for (Index =3D UcCount + WtCount + WbCount + WpCount; Index &= lt; UcCount + WtCount + WbCount + WpCount + WcCount; Index++) {
    >
    > +    GenerateRandomMtrrPair (PhysicalAddressBits, Cach= eWriteCombining, NULL, &RawMemoryRanges[Index]);
    >
    > +    while (RangesOverlap (&RawMemoryRanges[Index]= , &RawMemoryRanges[UcCount], WtCount + WbCount + WpCount)) {
    >
    > +      GenerateRandomMtrrPair (PhysicalAddre= ssBits, CacheWriteCombining, NULL, &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 r= ange 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    &nbs= p;            RangeC= ount
    >
    > +  )
    >
    > +{
    >
    > +  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[In= dex].
    >
    > +
    >
    > +  @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 &l= t; 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 (I= ndex, 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        &nbs= p;   Address,
    >
    > +  IN MTRR_MEMORY_RANGE Range
    >
    > +  )
    >
    > +{
    >
    > +    return (Address >=3D Range.BaseAddress) &&= amp; (Address <=3D Range.BaseAddress + Range.Length - 1);
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Get the overlap bit flag.
    >
    > +
    >
    > +  @param RawMemoryRanges     Raw memory ran= ges.
    >
    > +  @param RawMemoryRangeCount Count of raw memory ranges.
    >
    > +  @param Address        = ;     The address to check.
    >
    > +**/
    >
    > +UINT64
    >
    > +GetOverlapBitFlag (
    >
    > +  IN MTRR_MEMORY_RANGE *RawMemoryRanges,
    >
    > +  IN UINT32        &nbs= p;   RawMemoryRangeCount,
    >
    > +  IN UINT64        &nbs= p;   Address
    >
    > +  )
    >
    > +{
    >
    > +  UINT64 OverlapBitFlag;
    >
    > +  UINT32 Index;
    >
    > +  OverlapBitFlag =3D 0;
    >
    > +  for (Index =3D 0; Index < RawMemoryRangeCount; Index++) {<= br> >
    > +    if (AddressInRange (Address, RawMemoryRanges[Inde= x])) {
    >
    > +      OverlapBitFlag |=3D (1ull << In= dex);
    >
    > +    }
    >
    > +  }
    >
    > +
    >
    > +  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 F= lag2.
    >
    > +**/
    >
    > +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        &nbs= p;   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       &= nbsp;            Def= ault memory type.
    >
    > +  @param PhysicalAddressBits      = ;      Physical address bits.
    >
    > +  @param EffectiveMtrrMemoryRanges     = ; Memory ranges to compact.
    >
    > +  @param EffectiveMtrrMemoryRangesCount Return the new count of= memory ranges.
    >
    > +**/
    >
    > +VOID
    >
    > +CompactAndExtendEffectiveMtrrMemoryRanges (
    >
    > +  IN     MTRR_MEMORY_CACHE_TYPE DefaultType= ,
    >
    > +  IN     UINT32    &nbs= p;            Physic= alAddressBits,
    >
    > +  IN OUT MTRR_MEMORY_RANGE      **Effe= ctiveMtrrMemoryRanges,
    >
    > +  IN OUT UINTN        &= nbsp;         *EffectiveMtrrMemoryR= angesCount
    >
    > +  )
    >
    > +{
    >
    > +  UINT64         &= nbsp;           &nbs= p;  MaxAddress;
    >
    > +  UINTN         &n= bsp;            = ;   NewRangesCountAtMost;
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;     *NewRanges;
    >
    > +  UINTN         &n= bsp;            = ;   NewRangesCountActual;
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;     *CurrentRangeInNewRanges;
    >
    > +  MTRR_MEMORY_CACHE_TYPE      &nb= sp; CurrentRangeTypeInOldRanges;
    >
    > +
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;     *OldRanges;
    >
    > +  MTRR_MEMORY_RANGE       &n= bsp;     OldLastRange;
    >
    > +  UINTN         &n= bsp;            = ;   OldRangesIndex;
    >
    > +
    >
    > +  NewRangesCountActual =3D 0;
    >
    > +  NewRangesCountAtMost =3D *EffectiveMtrrMemoryRangesCount + 2;=    // At most with 2 more range entries.
    >
    > +  NewRanges        &nbs= p;   =3D (MTRR_MEMORY_RANGE *) calloc (NewRangesCountAtMost, size= of (MTRR_MEMORY_RANGE));
    >
    > +  OldRanges        &nbs= p;   =3D *EffectiveMtrrMemoryRanges;
    >
    > +  if (OldRanges[0].BaseAddress > 0) {
    >
    > +    NewRanges[NewRangesCountActual].BaseAddress =3D 0= ;
    >
    > +    NewRanges[NewRangesCountActual].Length  = ;    =3D OldRanges[0].BaseAddress;
    >
    > +    NewRanges[NewRangesCountActual].Type  &= nbsp;     =3D DefaultType;
    >
    > +    NewRangesCountActual++;
    >
    > +  }
    >
    > +
    >
    > +  OldRangesIndex =3D 0;
    >
    > +  while (OldRangesIndex < *EffectiveMtrrMemoryRangesCount) {=
    >
    > +    CurrentRangeTypeInOldRanges =3D OldRanges[OldRang= esIndex].Type;
    >
    > +    CurrentRangeInNewRanges =3D NULL;
    >
    > +    if (NewRangesCountActual > 0)   // W= e need to check CurrentNewRange first before generate a new NewRange.
    >
    > +    {
    >
    > +      CurrentRangeInNewRanges =3D &NewR= anges[NewRangesCountActual - 1];
    >
    > +    }
    >
    > +    if (CurrentRangeInNewRanges !=3D NULL && = CurrentRangeInNewRanges->Type =3D=3D CurrentRangeTypeInOldRanges) {
    >
    > +      CurrentRangeInNewRanges->Length += =3D OldRanges[OldRangesIndex].Length;
    >
    > +    } else {
    >
    > +      NewRanges[NewRangesCountActual].BaseA= ddress =3D OldRanges[OldRangesIndex].BaseAddress;
    >
    > +      NewRanges[NewRangesCountActual].Lengt= h     +=3D OldRanges[OldRangesIndex].Length;
    >
    > +      NewRanges[NewRangesCountActual].Type&= nbsp;       =3D CurrentRangeTypeInOldRanges;<= br> >
    > +      while (OldRangesIndex + 1 < *Effec= tiveMtrrMemoryRangesCount && OldRanges[OldRangesIndex + 1].Type =3D= = =3D CurrentRangeTypeInOldRanges)
    >
    > +      {
    >
    > +        OldRangesIndex++;
    >
    > +        NewRanges[NewRangesCountA= ctual].Length +=3D OldRanges[OldRangesIndex].Length;
    >
    > +      }
    >
    > +      NewRangesCountActual++;
    >
    > +    }
    >
    > +
    >
    > +    OldRangesIndex++;
    >
    > +  }
    >
    > +
    >
    > +  MaxAddress =3D (1ull << PhysicalAddressBits) - 1;
    >
    > +  OldLastRange =3D OldRanges[(*EffectiveMtrrMemoryRangesCount) = - 1];
    >
    > +  CurrentRangeInNewRanges =3D &NewRanges[NewRangesCountActu= al - 1];
    >
    > +  if (OldLastRange.BaseAddress + OldLastRange.Length - 1 < M= axAddress) {
    >
    > +    if (CurrentRangeInNewRanges->Type =3D=3D Defau= ltType) {
    >
    > +      CurrentRangeInNewRanges->Length = =3D MaxAddress - CurrentRangeInNewRanges->BaseAddress + 1;
    >
    > +    } else {
    >
    > +      NewRanges[NewRangesCountActual].BaseA= ddress =3D OldLastRange.BaseAddress + OldLastRange.Length;
    >
    > +      NewRanges[NewRangesCountActual].Lengt= h =3D MaxAddress - NewRanges[NewRangesCountActual].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       &nb= sp;   Return the collected endpoints.
    >
    > +  @param EndPointCount       Retu= rn the count of endpoints.
    >
    > +  @param RawMemoryRanges     Raw memory ran= ges.
    >
    > +  @param RawMemoryRangeCount Count of raw memory ranges.
    >
    > +**/
    >
    > +VOID
    >
    > +CollectEndpoints (
    >
    > +  IN OUT UINT64        *Endp= oints,
    >
    > +  IN OUT UINT32        *EndP= ointCount,
    >
    > +  IN MTRR_MEMORY_RANGE *RawMemoryRanges,
    >
    > +  IN UINT32        &nbs= p;   RawMemoryRangeCount
    >
    > +  )
    >
    > +{
    >
    > +  UINT32 Index;
    >
    > +  UINT32 RawRangeIndex;
    >
    > +
    >
    > +  ASSERT ((RawMemoryRangeCount << 1) =3D=3D *EndPointCoun= t);
    >
    > +
    >
    > +  for (Index =3D 0; Index < *EndPointCount; Index +=3D 2) {<= br> >
    > +    RawRangeIndex =3D Index >> 1;
    >
    > +    Endpoints[Index] =3D RawMemoryRanges[RawRangeInde= x].BaseAddress;
    >
    > +    Endpoints[Index + 1] =3D RawMemoryRanges[RawRange= Index].BaseAddress + RawMemoryRanges[RawRangeIndex].Length - 1;
    >
    > +  }
    >
    > +
    >
    > +  qsort (Endpoints, *EndPointCount, sizeof (UINT64), CompareFun= cUint64);
    >
    > +  RemoveDuplicatesInSortedArray (Endpoints, EndPointCount);
    >
    > +}
    >
    > +
    >
    > +/**
    >
    > +  Convert the MTRR BASE/MASK array to memory ranges.
    >
    > +
    >
    > +  @param DefaultType       &= nbsp;  Default memory type.
    >
    > +  @param PhysicalAddressBits  Physical address bits.
    >
    > +  @param RawMemoryRanges      Raw memo= ry ranges.
    >
    > +  @param RawMemoryRangeCount  Count of raw memory ranges.<= br> >
    > +  @param MemoryRanges       =   Memory ranges.
    >
    > +  @param MemoryRangeCount     Count of memo= ry ranges.
    >
    > +**/
    >
    > +VOID
    >
    > +GetEffectiveMemoryRanges (
    >
    > +  IN MTRR_MEMORY_CACHE_TYPE DefaultType,
    >
    > +  IN UINT32        &nbs= p;        PhysicalAddressBits,
    >
    > +  IN MTRR_MEMORY_RANGE      *RawMemory= Ranges,
    >
    > +  IN UINT32        &nbs= p;        RawMemoryRangeCount,
    >
    > +  OUT MTRR_MEMORY_RANGE     *MemoryRanges,<= br> >
    > +  OUT UINTN        &nbs= p;        *MemoryRangeCount
    >
    > +  )
    >
    > +{
    >
    > +  UINTN         &n= bsp;       Index;
    >
    > +  UINT32         &= nbsp;      AllEndPointsCount;
    >
    > +  UINT64         &= nbsp;      *AllEndPointsInclusive;
    >
    > +  UINT32         &= nbsp;      AllRangePiecesCountMax;
    >
    > +  MTRR_MEMORY_RANGE     *AllRangePieces; >
    > +  UINTN         &n= bsp;       AllRangePiecesCountActual;
    >
    > +  UINT64         &= nbsp;      OverlapBitFlag1;
    >
    > +  UINT64         &= nbsp;      OverlapBitFlag2;
    >
    > +  INT32         &n= bsp;       OverlapFlagRelation;
    >
    > +
    >
    > +  if (RawMemoryRangeCount =3D=3D 0) {
    >
    > +    MemoryRanges[0].BaseAddress =3D 0;
    >
    > +    MemoryRanges[0].Length    &nb= sp; =3D (1ull << PhysicalAddressBits);
    >
    > +    MemoryRanges[0].Type     = ;   =3D DefaultType;
    >
    > +    *MemoryRangeCount =3D 1;
    >
    > +    return;
    >
    > +  }
    >
    > +
    >
    > +  AllEndPointsCount       &n= bsp; =3D RawMemoryRangeCount << 1;
    >
    > +  AllEndPointsInclusive     =3D calloc (All= EndPointsCount, sizeof (UINT64));
    >
    > +  AllRangePiecesCountMax    =3D RawMemoryRangeCo= unt * 3 + 1;
    >
    > +  AllRangePieces        = ;    =3D calloc (AllRangePiecesCountMax, sizeof (MTRR_MEMORY= _RANGE));
    >
    > +  CollectEndpoints (AllEndPointsInclusive, &AllEndPointsCou= nt, RawMemoryRanges, RawMemoryRangeCount);
    >
    > +
    >
    > +  for (Index =3D 0, AllRangePiecesCountActual =3D 0; Index <= AllEndPointsCount - 1; Index++) {
    >
    > +    OverlapBitFlag1 =3D GetOverlapBitFlag (RawMemoryR= anges, RawMemoryRangeCount, AllEndPointsInclusive[Index]);
    >
    > +    OverlapBitFlag2 =3D GetOverlapBitFlag (RawMemoryR= anges, RawMemoryRangeCount, AllEndPointsInclusive[Index + 1]);
    >
    > +    OverlapFlagRelation =3D CheckOverlapBitFlagsRelat= ion (OverlapBitFlag1, OverlapBitFlag2);
    >
    > +    switch (OverlapFlagRelation) {
    >
    > +      case 0:   // [1, 2]
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].BaseAddress =3D AllEndPointsInclusive[Index];
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].Length      =3D AllEndPointsInclu= sive[Index + 1] - AllEndPointsInclusive[Index] + 1;
    >
    > +        AllRangePiecesCountActual= ++;
    >
    > +        break;
    >
    > +      case 1:   // [1, 2)
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].BaseAddress =3D AllEndPointsInclusive[Index];
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].Length      =3D (AllEndPointsIncl= usive[Index + 1] - 1) - AllEndPointsInclusive[Index] + 1;
    >
    > +        AllRangePiecesCountActual= ++;
    >
    > +        break;
    >
    > +      case 2:   // (1, 2]
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].BaseAddress =3D AllEndPointsInclusive[Index] + 1;
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].Length      =3D AllEndPointsInclu= sive[Index + 1] - (AllEndPointsInclusive[Index] + 1) + 1;
    >
    > +        AllRangePiecesCountActual= ++;
    >
    > +
    >
    > +        if (!IsEndpointInRanges (= AllEndPointsInclusive[Index], AllRangePieces, AllRangePiecesCountActual)) {=
    >
    > +          AllRangePiece= s[AllRangePiecesCountActual].BaseAddress =3D AllEndPointsInclusive[Index];<= br> >
    > +          AllRangePiece= s[AllRangePiecesCountActual].Length      =3D 1; >
    > +          AllRangePiece= sCountActual++;
    >
    > +        }
    >
    > +        break;
    >
    > +      case 3:   // (1, 2)
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].BaseAddress =3D AllEndPointsInclusive[Index] + 1;
    >
    > +        AllRangePieces[AllRangePi= ecesCountActual].Length      =3D (AllEndPointsIncl= usive[Index + 1] - 1) - (AllEndPointsInclusive[Index] + 1) + 1;
    >
    > +        if (AllRangePieces[AllRan= gePiecesCountActual].Length =3D=3D 0)   // Only in case 3 can exi= sts Length=3D0, we should skip such "segment".
    >
    > +          break;
    >
    > +        AllRangePiecesCountActual= ++;
    >
    > +        if (!IsEndpointInRanges (= AllEndPointsInclusive[Index], AllRangePieces, AllRangePiecesCountActual)) {=
    >
    > +          AllRangePiece= s[AllRangePiecesCountActual].BaseAddress =3D AllEndPointsInclusive[Index];<= br> >
    > +          AllRangePiece= s[AllRangePiecesCountActual].Length      =3D 1; >
    > +          AllRangePiece= sCountActual++;
    >
    > +        }
    >
    > +        break;
    >
    > +      default:
    >
    > +        ASSERT (FALSE);
    >
    > +    }
    >
    > +  }
    >
    > +
    >
    > +  for (Index =3D 0; Index < AllRangePiecesCountActual; Index= ++) {
    >
    > +    DetermineMemoryCacheType (DefaultType, &AllRa= ngePieces[Index], RawMemoryRanges, RawMemoryRangeCount);
    >
    > +  }
    >
    > +
    >
    > +  CompactAndExtendEffectiveMtrrMemoryRanges (DefaultType, Physi= calAddressBits, &AllRangePieces, &AllRangePiecesCountActual);
    >
    > +  ASSERT (*MemoryRangeCount >=3D AllRangePiecesCountActual);=
    >
    > +  memcpy (MemoryRanges, AllRangePieces, AllRangePiecesCountActu= al * sizeof (MTRR_MEMORY_RANGE));
    >
    > +  *MemoryRangeCount =3D AllRangePiecesCountActual;
    >
    > +
    >
    > +  free (AllEndPointsInclusive);
    >
    > +  free (AllRangePieces);
    >
    > +}
    >
    > diff --git a/UefiCpuPkg/Test/UefiCpuPkgHostTest.dsc b/UefiCpuPkg/Test= /UefiCpuPkgHostTest.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.<BR&= gt;
    >
    > +# 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 0x0= 0010005
    >
    > +  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": {
    >
    >           "Dsc= Path": "UefiCpuPkg.dsc"
    >
    >       },
    >
    > +    ## options defined ci/Plugin/HostUnitTestCompiler= Plugin
    >
    > +    "HostUnitTestCompilerPlugin": {
    >
    > +        "DscPath": &quo= t;Test/UefiCpuPkgHostTest.dsc"
    >
    > +    },
    >
    >       "CharEncodingCheck": {<= br> >
    >           "Ign= oreFiles": []
    >
    >       },
    >
    > @@ -18,7 +22,9 @@
    >           &nbs= p;   "UefiCpuPkg/UefiCpuPkg.dec"
    >
    >           ],
    >
    >           # For hos= t based unit tests
    >
    > -        "AcceptableDependenc= ies-HOST_APPLICATION":[],
    >
    > +        "AcceptableDependenc= ies-HOST_APPLICATION":[
    >
    > +            &= quot;UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec"
    >
    > +        ],
    >
    >           # For UEF= I shell based apps
    >
    >           "Acc= eptableDependencies-UEFI_APPLICATION":[],
    >
    >           "Ign= oreInf": []
    >
    > @@ -30,6 +36,10 @@
    >           &nbs= p;   "UefiCpuPkg/ResetVector/Vtf0/Vtf0.inf"
    >
    >           ]
    >
    >       },
    >
    > +    "HostUnitTestDscCompleteCheck": {
    >
    > +        "IgnoreInf": [&= quot;"],
    >
    > +        "DscPath": &quo= t;Test/UefiCpuPkgHostTest.dsc"
    >
    > +    },
    >
    >       "GuidCheck": {
    >
    >           "Ign= oreGuidName": ["SecCore", "ResetVector"], # Expect= ed duplication for gEfiFirmwareVolumeTopFileGuid
    >
    >           "Ign= oreGuidValue": [],
    >



     

--_000_CY4PR21MB07430EEAF012BC185B3DC28AEF730CY4PR21MB0743namp_--