Support.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /** @file
  2. Unit tests of the MtrrLib instance of the MtrrLib class
  3. Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.<BR>
  4. SPDX-License-Identifier: BSD-2-Clause-Patent
  5. **/
  6. #include "MtrrLibUnitTest.h"
  7. MTRR_MEMORY_CACHE_TYPE mMemoryCacheTypes[] = {
  8. CacheUncacheable, CacheWriteCombining, CacheWriteThrough, CacheWriteProtected, CacheWriteBack
  9. };
  10. UINT64 mFixedMtrrsValue[MTRR_NUMBER_OF_FIXED_MTRR];
  11. MSR_IA32_MTRR_PHYSBASE_REGISTER mVariableMtrrsPhysBase[MTRR_NUMBER_OF_VARIABLE_MTRR];
  12. MSR_IA32_MTRR_PHYSMASK_REGISTER mVariableMtrrsPhysMask[MTRR_NUMBER_OF_VARIABLE_MTRR];
  13. MSR_IA32_MTRR_DEF_TYPE_REGISTER mDefTypeMsr;
  14. MSR_IA32_MTRRCAP_REGISTER mMtrrCapMsr;
  15. CPUID_VERSION_INFO_EDX mCpuidVersionInfoEdx;
  16. CPUID_VIR_PHY_ADDRESS_SIZE_EAX mCpuidVirPhyAddressSizeEax;
  17. BOOLEAN mRandomInput;
  18. UINTN mNumberIndex = 0;
  19. extern UINTN mNumbers[];
  20. extern UINTN mNumberCount;
  21. /**
  22. Return a random number between 0 and RAND_MAX.
  23. If mRandomInput is TRUE, the routine directly calls rand().
  24. Otherwise, the routine returns the pre-generated numbers.
  25. @return a number between 0 and RAND_MAX.
  26. **/
  27. UINTN
  28. Rand (
  29. VOID
  30. )
  31. {
  32. if (mRandomInput) {
  33. return rand ();
  34. } else {
  35. DEBUG ((DEBUG_INFO, "random: %d\n", mNumberIndex));
  36. return mNumbers[mNumberIndex++ % (mNumberCount - 1)];
  37. }
  38. }
  39. CHAR8 mContentTemplate[] = {
  40. "/** @file\n"
  41. " Pre-generated random number used by MtrrLib test.\n"
  42. "\n"
  43. " Copyright (c) 2020, Intel Corporation. All rights reserved.<BR>\n"
  44. " SPDX-License-Identifier: BSD-2-Clause-Patent\n"
  45. "**/\n"
  46. "UINTN mNumberCount = %d;\n"
  47. "UINTN mNumbers[] = {"
  48. };
  49. /**
  50. Generate Count random numbers in FilePath.
  51. @param FilePath The file path to put the generated random numbers.
  52. @param Count Count of random numbers.
  53. **/
  54. VOID
  55. GenerateRandomNumbers (
  56. CHAR8 *FilePath,
  57. UINTN Count
  58. )
  59. {
  60. FILE *File;
  61. UINTN Index;
  62. File = fopen (FilePath, "w");
  63. fprintf (File, mContentTemplate, Count);
  64. for (Index = 0; Index < Count; Index++) {
  65. if (Index % 10 == 0) {
  66. fprintf (File, "\n ");
  67. }
  68. fprintf (File, " %d,", rand ());
  69. }
  70. fprintf (File, "\n};\n");
  71. fclose (File);
  72. }
  73. /**
  74. Retrieves CPUID information.
  75. Executes the CPUID instruction with EAX set to the value specified by Index.
  76. This function always returns Index.
  77. If Eax is not NULL, then the value of EAX after CPUID is returned in Eax.
  78. If Ebx is not NULL, then the value of EBX after CPUID is returned in Ebx.
  79. If Ecx is not NULL, then the value of ECX after CPUID is returned in Ecx.
  80. If Edx is not NULL, then the value of EDX after CPUID is returned in Edx.
  81. This function is only available on IA-32 and x64.
  82. @param Index The 32-bit value to load into EAX prior to invoking the CPUID
  83. instruction.
  84. @param Eax The pointer to the 32-bit EAX value returned by the CPUID
  85. instruction. This is an optional parameter that may be NULL.
  86. @param Ebx The pointer to the 32-bit EBX value returned by the CPUID
  87. instruction. This is an optional parameter that may be NULL.
  88. @param Ecx The pointer to the 32-bit ECX value returned by the CPUID
  89. instruction. This is an optional parameter that may be NULL.
  90. @param Edx The pointer to the 32-bit EDX value returned by the CPUID
  91. instruction. This is an optional parameter that may be NULL.
  92. @return Index.
  93. **/
  94. UINT32
  95. EFIAPI
  96. UnitTestMtrrLibAsmCpuid (
  97. IN UINT32 Index,
  98. OUT UINT32 *Eax OPTIONAL,
  99. OUT UINT32 *Ebx OPTIONAL,
  100. OUT UINT32 *Ecx OPTIONAL,
  101. OUT UINT32 *Edx OPTIONAL
  102. )
  103. {
  104. switch (Index) {
  105. case CPUID_VERSION_INFO:
  106. if (Edx != NULL) {
  107. *Edx = mCpuidVersionInfoEdx.Uint32;
  108. }
  109. return Index;
  110. break;
  111. case CPUID_EXTENDED_FUNCTION:
  112. if (Eax != NULL) {
  113. *Eax = CPUID_VIR_PHY_ADDRESS_SIZE;
  114. }
  115. return Index;
  116. break;
  117. case CPUID_VIR_PHY_ADDRESS_SIZE:
  118. if (Eax != NULL) {
  119. *Eax = mCpuidVirPhyAddressSizeEax.Uint32;
  120. }
  121. return Index;
  122. break;
  123. }
  124. //
  125. // Should never fall through to here
  126. //
  127. ASSERT (FALSE);
  128. return Index;
  129. }
  130. /**
  131. Returns a 64-bit Machine Specific Register(MSR).
  132. Reads and returns the 64-bit MSR specified by Index. No parameter checking is
  133. performed on Index, and some Index values may cause CPU exceptions. The
  134. caller must either guarantee that Index is valid, or the caller must set up
  135. exception handlers to catch the exceptions. This function is only available
  136. on IA-32 and x64.
  137. @param MsrIndex The 32-bit MSR index to read.
  138. @return The value of the MSR identified by MsrIndex.
  139. **/
  140. UINT64
  141. EFIAPI
  142. UnitTestMtrrLibAsmReadMsr64 (
  143. IN UINT32 MsrIndex
  144. )
  145. {
  146. UINT32 Index;
  147. for (Index = 0; Index < ARRAY_SIZE (mFixedMtrrsValue); Index++) {
  148. if (MsrIndex == mFixedMtrrsIndex[Index]) {
  149. return mFixedMtrrsValue[Index];
  150. }
  151. }
  152. if ((MsrIndex >= MSR_IA32_MTRR_PHYSBASE0) &&
  153. (MsrIndex <= MSR_IA32_MTRR_PHYSMASK0 + (MTRR_NUMBER_OF_VARIABLE_MTRR << 1)))
  154. {
  155. if (MsrIndex % 2 == 0) {
  156. Index = (MsrIndex - MSR_IA32_MTRR_PHYSBASE0) >> 1;
  157. return mVariableMtrrsPhysBase[Index].Uint64;
  158. } else {
  159. Index = (MsrIndex - MSR_IA32_MTRR_PHYSMASK0) >> 1;
  160. return mVariableMtrrsPhysMask[Index].Uint64;
  161. }
  162. }
  163. if (MsrIndex == MSR_IA32_MTRR_DEF_TYPE) {
  164. return mDefTypeMsr.Uint64;
  165. }
  166. if (MsrIndex == MSR_IA32_MTRRCAP) {
  167. return mMtrrCapMsr.Uint64;
  168. }
  169. //
  170. // Should never fall through to here
  171. //
  172. ASSERT (FALSE);
  173. return 0;
  174. }
  175. /**
  176. Writes a 64-bit value to a Machine Specific Register(MSR), and returns the
  177. value.
  178. Writes the 64-bit value specified by Value to the MSR specified by Index. The
  179. 64-bit value written to the MSR is returned. No parameter checking is
  180. performed on Index or Value, and some of these may cause CPU exceptions. The
  181. caller must either guarantee that Index and Value are valid, or the caller
  182. must establish proper exception handlers. This function is only available on
  183. IA-32 and x64.
  184. @param MsrIndex The 32-bit MSR index to write.
  185. @param Value The 64-bit value to write to the MSR.
  186. @return Value
  187. **/
  188. UINT64
  189. EFIAPI
  190. UnitTestMtrrLibAsmWriteMsr64 (
  191. IN UINT32 MsrIndex,
  192. IN UINT64 Value
  193. )
  194. {
  195. UINT32 Index;
  196. for (Index = 0; Index < ARRAY_SIZE (mFixedMtrrsValue); Index++) {
  197. if (MsrIndex == mFixedMtrrsIndex[Index]) {
  198. mFixedMtrrsValue[Index] = Value;
  199. return Value;
  200. }
  201. }
  202. if ((MsrIndex >= MSR_IA32_MTRR_PHYSBASE0) &&
  203. (MsrIndex <= MSR_IA32_MTRR_PHYSMASK0 + (MTRR_NUMBER_OF_VARIABLE_MTRR << 1)))
  204. {
  205. if (MsrIndex % 2 == 0) {
  206. Index = (MsrIndex - MSR_IA32_MTRR_PHYSBASE0) >> 1;
  207. mVariableMtrrsPhysBase[Index].Uint64 = Value;
  208. return Value;
  209. } else {
  210. Index = (MsrIndex - MSR_IA32_MTRR_PHYSMASK0) >> 1;
  211. mVariableMtrrsPhysMask[Index].Uint64 = Value;
  212. return Value;
  213. }
  214. }
  215. if (MsrIndex == MSR_IA32_MTRR_DEF_TYPE) {
  216. mDefTypeMsr.Uint64 = Value;
  217. return Value;
  218. }
  219. if (MsrIndex == MSR_IA32_MTRRCAP) {
  220. mMtrrCapMsr.Uint64 = Value;
  221. return Value;
  222. }
  223. //
  224. // Should never fall through to here
  225. //
  226. ASSERT (FALSE);
  227. return 0;
  228. }
  229. /**
  230. Initialize the MTRR registers.
  231. @param SystemParameter System parameter that controls the MTRR registers initialization.
  232. **/
  233. UNIT_TEST_STATUS
  234. EFIAPI
  235. InitializeMtrrRegs (
  236. IN MTRR_LIB_SYSTEM_PARAMETER *SystemParameter
  237. )
  238. {
  239. UINT32 Index;
  240. SetMem (mFixedMtrrsValue, sizeof (mFixedMtrrsValue), SystemParameter->DefaultCacheType);
  241. for (Index = 0; Index < ARRAY_SIZE (mVariableMtrrsPhysBase); Index++) {
  242. mVariableMtrrsPhysBase[Index].Uint64 = 0;
  243. mVariableMtrrsPhysBase[Index].Bits.Type = SystemParameter->DefaultCacheType;
  244. mVariableMtrrsPhysBase[Index].Bits.Reserved1 = 0;
  245. mVariableMtrrsPhysMask[Index].Uint64 = 0;
  246. mVariableMtrrsPhysMask[Index].Bits.V = 0;
  247. mVariableMtrrsPhysMask[Index].Bits.Reserved1 = 0;
  248. }
  249. mDefTypeMsr.Bits.E = 1;
  250. mDefTypeMsr.Bits.FE = 1;
  251. mDefTypeMsr.Bits.Type = SystemParameter->DefaultCacheType;
  252. mDefTypeMsr.Bits.Reserved1 = 0;
  253. mDefTypeMsr.Bits.Reserved2 = 0;
  254. mDefTypeMsr.Bits.Reserved3 = 0;
  255. mMtrrCapMsr.Bits.SMRR = 0;
  256. mMtrrCapMsr.Bits.WC = 0;
  257. mMtrrCapMsr.Bits.VCNT = SystemParameter->VariableMtrrCount;
  258. mMtrrCapMsr.Bits.FIX = SystemParameter->FixedMtrrSupported;
  259. mMtrrCapMsr.Bits.Reserved1 = 0;
  260. mMtrrCapMsr.Bits.Reserved2 = 0;
  261. mMtrrCapMsr.Bits.Reserved3 = 0;
  262. mCpuidVersionInfoEdx.Bits.MTRR = SystemParameter->MtrrSupported;
  263. mCpuidVirPhyAddressSizeEax.Bits.PhysicalAddressBits = SystemParameter->PhysicalAddressBits;
  264. //
  265. // Hook BaseLib functions used by MtrrLib that require some emulation.
  266. //
  267. gUnitTestHostBaseLib.X86->AsmCpuid = UnitTestMtrrLibAsmCpuid;
  268. gUnitTestHostBaseLib.X86->AsmReadMsr64 = UnitTestMtrrLibAsmReadMsr64;
  269. gUnitTestHostBaseLib.X86->AsmWriteMsr64 = UnitTestMtrrLibAsmWriteMsr64;
  270. return UNIT_TEST_PASSED;
  271. }
  272. /**
  273. Initialize the MTRR registers.
  274. @param Context System parameter that controls the MTRR registers initialization.
  275. **/
  276. UNIT_TEST_STATUS
  277. EFIAPI
  278. InitializeSystem (
  279. IN UNIT_TEST_CONTEXT Context
  280. )
  281. {
  282. return InitializeMtrrRegs ((MTRR_LIB_SYSTEM_PARAMETER *)Context);
  283. }
  284. /**
  285. Collect the test result.
  286. @param DefaultType Default memory type.
  287. @param PhysicalAddressBits Physical address bits.
  288. @param VariableMtrrCount Count of variable MTRRs.
  289. @param Mtrrs MTRR settings to collect from.
  290. @param Ranges Return the memory ranges.
  291. @param RangeCount Return the count of memory ranges.
  292. @param MtrrCount Return the count of variable MTRRs being used.
  293. **/
  294. VOID
  295. CollectTestResult (
  296. IN MTRR_MEMORY_CACHE_TYPE DefaultType,
  297. IN UINT32 PhysicalAddressBits,
  298. IN UINT32 VariableMtrrCount,
  299. IN MTRR_SETTINGS *Mtrrs,
  300. OUT MTRR_MEMORY_RANGE *Ranges,
  301. IN OUT UINTN *RangeCount,
  302. OUT UINT32 *MtrrCount
  303. )
  304. {
  305. UINTN Index;
  306. UINT64 MtrrValidBitsMask;
  307. UINT64 MtrrValidAddressMask;
  308. MTRR_MEMORY_RANGE RawMemoryRanges[ARRAY_SIZE (Mtrrs->Variables.Mtrr)];
  309. ASSERT (Mtrrs != NULL);
  310. ASSERT (VariableMtrrCount <= ARRAY_SIZE (Mtrrs->Variables.Mtrr));
  311. MtrrValidBitsMask = (1ull << PhysicalAddressBits) - 1;
  312. MtrrValidAddressMask = MtrrValidBitsMask & ~0xFFFull;
  313. *MtrrCount = 0;
  314. for (Index = 0; Index < VariableMtrrCount; Index++) {
  315. if (((MSR_IA32_MTRR_PHYSMASK_REGISTER *)&Mtrrs->Variables.Mtrr[Index].Mask)->Bits.V == 1) {
  316. RawMemoryRanges[*MtrrCount].BaseAddress = Mtrrs->Variables.Mtrr[Index].Base & MtrrValidAddressMask;
  317. RawMemoryRanges[*MtrrCount].Type =
  318. ((MSR_IA32_MTRR_PHYSBASE_REGISTER *)&Mtrrs->Variables.Mtrr[Index].Base)->Bits.Type;
  319. RawMemoryRanges[*MtrrCount].Length =
  320. ((~(Mtrrs->Variables.Mtrr[Index].Mask & MtrrValidAddressMask)) & MtrrValidBitsMask) + 1;
  321. (*MtrrCount)++;
  322. }
  323. }
  324. GetEffectiveMemoryRanges (DefaultType, PhysicalAddressBits, RawMemoryRanges, *MtrrCount, Ranges, RangeCount);
  325. }
  326. /**
  327. Return a 32bit random number.
  328. @param Start Start of the random number range.
  329. @param Limit Limit of the random number range.
  330. @return 32bit random number
  331. **/
  332. UINT32
  333. Random32 (
  334. UINT32 Start,
  335. UINT32 Limit
  336. )
  337. {
  338. return (UINT32)(((double)Rand () / RAND_MAX) * (Limit - Start)) + Start;
  339. }
  340. /**
  341. Return a 64bit random number.
  342. @param Start Start of the random number range.
  343. @param Limit Limit of the random number range.
  344. @return 64bit random number
  345. **/
  346. UINT64
  347. Random64 (
  348. UINT64 Start,
  349. UINT64 Limit
  350. )
  351. {
  352. return (UINT64)(((double)Rand () / RAND_MAX) * (Limit - Start)) + Start;
  353. }
  354. /**
  355. Generate random MTRR BASE/MASK for a specified type.
  356. @param PhysicalAddressBits Physical address bits.
  357. @param CacheType Cache type.
  358. @param MtrrPair Return the random MTRR.
  359. @param MtrrMemoryRange Return the random memory range.
  360. **/
  361. VOID
  362. GenerateRandomMtrrPair (
  363. IN UINT32 PhysicalAddressBits,
  364. IN MTRR_MEMORY_CACHE_TYPE CacheType,
  365. OUT MTRR_VARIABLE_SETTING *MtrrPair OPTIONAL,
  366. OUT MTRR_MEMORY_RANGE *MtrrMemoryRange OPTIONAL
  367. )
  368. {
  369. MSR_IA32_MTRR_PHYSBASE_REGISTER PhysBase;
  370. MSR_IA32_MTRR_PHYSMASK_REGISTER PhysMask;
  371. UINT32 SizeShift;
  372. UINT32 BaseShift;
  373. UINT64 RandomBoundary;
  374. UINT64 MaxPhysicalAddress;
  375. UINT64 RangeSize;
  376. UINT64 RangeBase;
  377. UINT64 PhysBasePhyMaskValidBitsMask;
  378. MaxPhysicalAddress = 1ull << PhysicalAddressBits;
  379. do {
  380. SizeShift = Random32 (12, PhysicalAddressBits - 1);
  381. RangeSize = 1ull << SizeShift;
  382. BaseShift = Random32 (SizeShift, PhysicalAddressBits - 1);
  383. RandomBoundary = Random64 (0, 1ull << (PhysicalAddressBits - BaseShift));
  384. RangeBase = RandomBoundary << BaseShift;
  385. } while (RangeBase < SIZE_1MB || RangeBase > MaxPhysicalAddress - 1);
  386. PhysBasePhyMaskValidBitsMask = (MaxPhysicalAddress - 1) & 0xfffffffffffff000ULL;
  387. PhysBase.Uint64 = 0;
  388. PhysBase.Bits.Type = CacheType;
  389. PhysBase.Uint64 |= RangeBase & PhysBasePhyMaskValidBitsMask;
  390. PhysMask.Uint64 = 0;
  391. PhysMask.Bits.V = 1;
  392. PhysMask.Uint64 |= ((~RangeSize) + 1) & PhysBasePhyMaskValidBitsMask;
  393. if (MtrrPair != NULL) {
  394. MtrrPair->Base = PhysBase.Uint64;
  395. MtrrPair->Mask = PhysMask.Uint64;
  396. }
  397. if (MtrrMemoryRange != NULL) {
  398. MtrrMemoryRange->BaseAddress = RangeBase;
  399. MtrrMemoryRange->Length = RangeSize;
  400. MtrrMemoryRange->Type = CacheType;
  401. }
  402. }
  403. /**
  404. Check whether the Range overlaps with any one in Ranges.
  405. @param Range The memory range to check.
  406. @param Ranges The memory ranges.
  407. @param Count Count of memory ranges.
  408. @return TRUE when overlap exists.
  409. **/
  410. BOOLEAN
  411. RangesOverlap (
  412. IN MTRR_MEMORY_RANGE *Range,
  413. IN MTRR_MEMORY_RANGE *Ranges,
  414. IN UINTN Count
  415. )
  416. {
  417. while (Count-- != 0) {
  418. //
  419. // Two ranges overlap when:
  420. // 1. range#2.base is in the middle of range#1
  421. // 2. range#1.base is in the middle of range#2
  422. //
  423. if ( ((Range->BaseAddress <= Ranges[Count].BaseAddress) && (Ranges[Count].BaseAddress < Range->BaseAddress + Range->Length))
  424. || ((Ranges[Count].BaseAddress <= Range->BaseAddress) && (Range->BaseAddress < Ranges[Count].BaseAddress + Ranges[Count].Length)))
  425. {
  426. return TRUE;
  427. }
  428. }
  429. return FALSE;
  430. }
  431. /**
  432. Generate random MTRRs.
  433. @param PhysicalAddressBits Physical address bits.
  434. @param RawMemoryRanges Return the randomly generated MTRRs.
  435. @param UcCount Count of Uncacheable MTRRs.
  436. @param WtCount Count of Write Through MTRRs.
  437. @param WbCount Count of Write Back MTRRs.
  438. @param WpCount Count of Write Protected MTRRs.
  439. @param WcCount Count of Write Combine MTRRs.
  440. **/
  441. VOID
  442. GenerateValidAndConfigurableMtrrPairs (
  443. IN UINT32 PhysicalAddressBits,
  444. IN OUT MTRR_MEMORY_RANGE *RawMemoryRanges,
  445. IN UINT32 UcCount,
  446. IN UINT32 WtCount,
  447. IN UINT32 WbCount,
  448. IN UINT32 WpCount,
  449. IN UINT32 WcCount
  450. )
  451. {
  452. UINT32 Index;
  453. //
  454. // 1. Generate UC, WT, WB in order.
  455. //
  456. for (Index = 0; Index < UcCount; Index++) {
  457. GenerateRandomMtrrPair (PhysicalAddressBits, CacheUncacheable, NULL, &RawMemoryRanges[Index]);
  458. }
  459. for (Index = UcCount; Index < UcCount + WtCount; Index++) {
  460. GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteThrough, NULL, &RawMemoryRanges[Index]);
  461. }
  462. for (Index = UcCount + WtCount; Index < UcCount + WtCount + WbCount; Index++) {
  463. GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteBack, NULL, &RawMemoryRanges[Index]);
  464. }
  465. //
  466. // 2. Generate WP MTRR and DO NOT overlap with WT, WB.
  467. //
  468. for (Index = UcCount + WtCount + WbCount; Index < UcCount + WtCount + WbCount + WpCount; Index++) {
  469. GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteProtected, NULL, &RawMemoryRanges[Index]);
  470. while (RangesOverlap (&RawMemoryRanges[Index], &RawMemoryRanges[UcCount], WtCount + WbCount)) {
  471. GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteProtected, NULL, &RawMemoryRanges[Index]);
  472. }
  473. }
  474. //
  475. // 3. Generate WC MTRR and DO NOT overlap with WT, WB, WP.
  476. //
  477. for (Index = UcCount + WtCount + WbCount + WpCount; Index < UcCount + WtCount + WbCount + WpCount + WcCount; Index++) {
  478. GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteCombining, NULL, &RawMemoryRanges[Index]);
  479. while (RangesOverlap (&RawMemoryRanges[Index], &RawMemoryRanges[UcCount], WtCount + WbCount + WpCount)) {
  480. GenerateRandomMtrrPair (PhysicalAddressBits, CacheWriteCombining, NULL, &RawMemoryRanges[Index]);
  481. }
  482. }
  483. }
  484. /**
  485. Return a random memory cache type.
  486. **/
  487. MTRR_MEMORY_CACHE_TYPE
  488. GenerateRandomCacheType (
  489. VOID
  490. )
  491. {
  492. return mMemoryCacheTypes[Random32 (0, ARRAY_SIZE (mMemoryCacheTypes) - 1)];
  493. }
  494. /**
  495. Compare function used by qsort().
  496. **/
  497. /**
  498. Compare function used by qsort().
  499. @param Left Left operand to compare.
  500. @param Right Right operand to compare.
  501. @retval 0 Left == Right
  502. @retval -1 Left < Right
  503. @retval 1 Left > Right
  504. **/
  505. INT32
  506. CompareFuncUint64 (
  507. CONST VOID *Left,
  508. CONST VOID *Right
  509. )
  510. {
  511. INT64 Delta;
  512. Delta = (*(UINT64 *)Left - *(UINT64 *)Right);
  513. if (Delta > 0) {
  514. return 1;
  515. } else if (Delta == 0) {
  516. return 0;
  517. } else {
  518. return -1;
  519. }
  520. }
  521. /**
  522. Determin the memory cache type for the Range.
  523. @param DefaultType Default cache type.
  524. @param Range The memory range to determin the cache type.
  525. @param Ranges The entire memory ranges.
  526. @param RangeCount Count of the entire memory ranges.
  527. **/
  528. VOID
  529. DetermineMemoryCacheType (
  530. IN MTRR_MEMORY_CACHE_TYPE DefaultType,
  531. IN OUT MTRR_MEMORY_RANGE *Range,
  532. IN MTRR_MEMORY_RANGE *Ranges,
  533. IN UINT32 RangeCount
  534. )
  535. {
  536. UINT32 Index;
  537. Range->Type = CacheInvalid;
  538. for (Index = 0; Index < RangeCount; Index++) {
  539. if (RangesOverlap (Range, &Ranges[Index], 1)) {
  540. if (Ranges[Index].Type < Range->Type) {
  541. Range->Type = Ranges[Index].Type;
  542. }
  543. }
  544. }
  545. if (Range->Type == CacheInvalid) {
  546. Range->Type = DefaultType;
  547. }
  548. }
  549. /**
  550. Get the index of the element that does NOT equals to Array[Index].
  551. @param Index Current element.
  552. @param Array Array to scan.
  553. @param Count Count of the array.
  554. @return Next element that doesn't equal to current one.
  555. **/
  556. UINT32
  557. GetNextDifferentElementInSortedArray (
  558. IN UINT32 Index,
  559. IN UINT64 *Array,
  560. IN UINT32 Count
  561. )
  562. {
  563. UINT64 CurrentElement;
  564. CurrentElement = Array[Index];
  565. while (CurrentElement == Array[Index] && Index < Count) {
  566. Index++;
  567. }
  568. return Index;
  569. }
  570. /**
  571. Remove the duplicates from the array.
  572. @param Array The array to operate on.
  573. @param Count Count of the array.
  574. **/
  575. VOID
  576. RemoveDuplicatesInSortedArray (
  577. IN OUT UINT64 *Array,
  578. IN OUT UINT32 *Count
  579. )
  580. {
  581. UINT32 Index;
  582. UINT32 NewCount;
  583. Index = 0;
  584. NewCount = 0;
  585. while (Index < *Count) {
  586. Array[NewCount] = Array[Index];
  587. NewCount++;
  588. Index = GetNextDifferentElementInSortedArray (Index, Array, *Count);
  589. }
  590. *Count = NewCount;
  591. }
  592. /**
  593. Return TRUE when Address is in the Range.
  594. @param Address The address to check.
  595. @param Range The range to check.
  596. @return TRUE when Address is in the Range.
  597. **/
  598. BOOLEAN
  599. AddressInRange (
  600. IN UINT64 Address,
  601. IN MTRR_MEMORY_RANGE Range
  602. )
  603. {
  604. return (Address >= Range.BaseAddress) && (Address <= Range.BaseAddress + Range.Length - 1);
  605. }
  606. /**
  607. Get the overlap bit flag.
  608. @param RawMemoryRanges Raw memory ranges.
  609. @param RawMemoryRangeCount Count of raw memory ranges.
  610. @param Address The address to check.
  611. **/
  612. UINT64
  613. GetOverlapBitFlag (
  614. IN MTRR_MEMORY_RANGE *RawMemoryRanges,
  615. IN UINT32 RawMemoryRangeCount,
  616. IN UINT64 Address
  617. )
  618. {
  619. UINT64 OverlapBitFlag;
  620. UINT32 Index;
  621. OverlapBitFlag = 0;
  622. for (Index = 0; Index < RawMemoryRangeCount; Index++) {
  623. if (AddressInRange (Address, RawMemoryRanges[Index])) {
  624. OverlapBitFlag |= (1ull << Index);
  625. }
  626. }
  627. return OverlapBitFlag;
  628. }
  629. /**
  630. Return the relationship between flags.
  631. @param Flag1 Flag 1
  632. @param Flag2 Flag 2
  633. @retval 0 Flag1 == Flag2
  634. @retval 1 Flag1 is a subset of Flag2
  635. @retval 2 Flag2 is a subset of Flag1
  636. @retval 3 No subset relations between Flag1 and Flag2.
  637. **/
  638. UINT32
  639. CheckOverlapBitFlagsRelation (
  640. IN UINT64 Flag1,
  641. IN UINT64 Flag2
  642. )
  643. {
  644. if (Flag1 == Flag2) {
  645. return 0;
  646. }
  647. if ((Flag1 | Flag2) == Flag2) {
  648. return 1;
  649. }
  650. if ((Flag1 | Flag2) == Flag1) {
  651. return 2;
  652. }
  653. return 3;
  654. }
  655. /**
  656. Return TRUE when the Endpoint is in any of the Ranges.
  657. @param Endpoint The endpoint to check.
  658. @param Ranges The memory ranges.
  659. @param RangeCount Count of memory ranges.
  660. @retval TRUE Endpoint is in one of the range.
  661. @retval FALSE Endpoint is not in any of the ranges.
  662. **/
  663. BOOLEAN
  664. IsEndpointInRanges (
  665. IN UINT64 Endpoint,
  666. IN MTRR_MEMORY_RANGE *Ranges,
  667. IN UINTN RangeCount
  668. )
  669. {
  670. UINT32 Index;
  671. for (Index = 0; Index < RangeCount; Index++) {
  672. if (AddressInRange (Endpoint, Ranges[Index])) {
  673. return TRUE;
  674. }
  675. }
  676. return FALSE;
  677. }
  678. /**
  679. Compact adjacent ranges of the same type.
  680. @param DefaultType Default memory type.
  681. @param PhysicalAddressBits Physical address bits.
  682. @param EffectiveMtrrMemoryRanges Memory ranges to compact.
  683. @param EffectiveMtrrMemoryRangesCount Return the new count of memory ranges.
  684. **/
  685. VOID
  686. CompactAndExtendEffectiveMtrrMemoryRanges (
  687. IN MTRR_MEMORY_CACHE_TYPE DefaultType,
  688. IN UINT32 PhysicalAddressBits,
  689. IN OUT MTRR_MEMORY_RANGE **EffectiveMtrrMemoryRanges,
  690. IN OUT UINTN *EffectiveMtrrMemoryRangesCount
  691. )
  692. {
  693. UINT64 MaxAddress;
  694. UINTN NewRangesCountAtMost;
  695. MTRR_MEMORY_RANGE *NewRanges;
  696. UINTN NewRangesCountActual;
  697. MTRR_MEMORY_RANGE *CurrentRangeInNewRanges;
  698. MTRR_MEMORY_CACHE_TYPE CurrentRangeTypeInOldRanges;
  699. MTRR_MEMORY_RANGE *OldRanges;
  700. MTRR_MEMORY_RANGE OldLastRange;
  701. UINTN OldRangesIndex;
  702. NewRangesCountActual = 0;
  703. NewRangesCountAtMost = *EffectiveMtrrMemoryRangesCount + 2; // At most with 2 more range entries.
  704. NewRanges = (MTRR_MEMORY_RANGE *)calloc (NewRangesCountAtMost, sizeof (MTRR_MEMORY_RANGE));
  705. OldRanges = *EffectiveMtrrMemoryRanges;
  706. if (OldRanges[0].BaseAddress > 0) {
  707. NewRanges[NewRangesCountActual].BaseAddress = 0;
  708. NewRanges[NewRangesCountActual].Length = OldRanges[0].BaseAddress;
  709. NewRanges[NewRangesCountActual].Type = DefaultType;
  710. NewRangesCountActual++;
  711. }
  712. OldRangesIndex = 0;
  713. while (OldRangesIndex < *EffectiveMtrrMemoryRangesCount) {
  714. CurrentRangeTypeInOldRanges = OldRanges[OldRangesIndex].Type;
  715. CurrentRangeInNewRanges = NULL;
  716. if (NewRangesCountActual > 0) {
  717. // We need to check CurrentNewRange first before generate a new NewRange.
  718. CurrentRangeInNewRanges = &NewRanges[NewRangesCountActual - 1];
  719. }
  720. if ((CurrentRangeInNewRanges != NULL) && (CurrentRangeInNewRanges->Type == CurrentRangeTypeInOldRanges)) {
  721. CurrentRangeInNewRanges->Length += OldRanges[OldRangesIndex].Length;
  722. } else {
  723. NewRanges[NewRangesCountActual].BaseAddress = OldRanges[OldRangesIndex].BaseAddress;
  724. NewRanges[NewRangesCountActual].Length += OldRanges[OldRangesIndex].Length;
  725. NewRanges[NewRangesCountActual].Type = CurrentRangeTypeInOldRanges;
  726. while (OldRangesIndex + 1 < *EffectiveMtrrMemoryRangesCount && OldRanges[OldRangesIndex + 1].Type == CurrentRangeTypeInOldRanges) {
  727. OldRangesIndex++;
  728. NewRanges[NewRangesCountActual].Length += OldRanges[OldRangesIndex].Length;
  729. }
  730. NewRangesCountActual++;
  731. }
  732. OldRangesIndex++;
  733. }
  734. MaxAddress = (1ull << PhysicalAddressBits) - 1;
  735. OldLastRange = OldRanges[(*EffectiveMtrrMemoryRangesCount) - 1];
  736. CurrentRangeInNewRanges = &NewRanges[NewRangesCountActual - 1];
  737. if (OldLastRange.BaseAddress + OldLastRange.Length - 1 < MaxAddress) {
  738. if (CurrentRangeInNewRanges->Type == DefaultType) {
  739. CurrentRangeInNewRanges->Length = MaxAddress - CurrentRangeInNewRanges->BaseAddress + 1;
  740. } else {
  741. NewRanges[NewRangesCountActual].BaseAddress = OldLastRange.BaseAddress + OldLastRange.Length;
  742. NewRanges[NewRangesCountActual].Length = MaxAddress - NewRanges[NewRangesCountActual].BaseAddress + 1;
  743. NewRanges[NewRangesCountActual].Type = DefaultType;
  744. NewRangesCountActual++;
  745. }
  746. }
  747. free (*EffectiveMtrrMemoryRanges);
  748. *EffectiveMtrrMemoryRanges = NewRanges;
  749. *EffectiveMtrrMemoryRangesCount = NewRangesCountActual;
  750. }
  751. /**
  752. Collect all the endpoints in the raw memory ranges.
  753. @param Endpoints Return the collected endpoints.
  754. @param EndPointCount Return the count of endpoints.
  755. @param RawMemoryRanges Raw memory ranges.
  756. @param RawMemoryRangeCount Count of raw memory ranges.
  757. **/
  758. VOID
  759. CollectEndpoints (
  760. IN OUT UINT64 *Endpoints,
  761. IN OUT UINT32 *EndPointCount,
  762. IN MTRR_MEMORY_RANGE *RawMemoryRanges,
  763. IN UINT32 RawMemoryRangeCount
  764. )
  765. {
  766. UINT32 Index;
  767. UINT32 RawRangeIndex;
  768. ASSERT ((RawMemoryRangeCount << 1) == *EndPointCount);
  769. for (Index = 0; Index < *EndPointCount; Index += 2) {
  770. RawRangeIndex = Index >> 1;
  771. Endpoints[Index] = RawMemoryRanges[RawRangeIndex].BaseAddress;
  772. Endpoints[Index + 1] = RawMemoryRanges[RawRangeIndex].BaseAddress + RawMemoryRanges[RawRangeIndex].Length - 1;
  773. }
  774. qsort (Endpoints, *EndPointCount, sizeof (UINT64), CompareFuncUint64);
  775. RemoveDuplicatesInSortedArray (Endpoints, EndPointCount);
  776. }
  777. /**
  778. Convert the MTRR BASE/MASK array to memory ranges.
  779. @param DefaultType Default memory type.
  780. @param PhysicalAddressBits Physical address bits.
  781. @param RawMemoryRanges Raw memory ranges.
  782. @param RawMemoryRangeCount Count of raw memory ranges.
  783. @param MemoryRanges Memory ranges.
  784. @param MemoryRangeCount Count of memory ranges.
  785. **/
  786. VOID
  787. GetEffectiveMemoryRanges (
  788. IN MTRR_MEMORY_CACHE_TYPE DefaultType,
  789. IN UINT32 PhysicalAddressBits,
  790. IN MTRR_MEMORY_RANGE *RawMemoryRanges,
  791. IN UINT32 RawMemoryRangeCount,
  792. OUT MTRR_MEMORY_RANGE *MemoryRanges,
  793. OUT UINTN *MemoryRangeCount
  794. )
  795. {
  796. UINTN Index;
  797. UINT32 AllEndPointsCount;
  798. UINT64 *AllEndPointsInclusive;
  799. UINT32 AllRangePiecesCountMax;
  800. MTRR_MEMORY_RANGE *AllRangePieces;
  801. UINTN AllRangePiecesCountActual;
  802. UINT64 OverlapBitFlag1;
  803. UINT64 OverlapBitFlag2;
  804. INT32 OverlapFlagRelation;
  805. if (RawMemoryRangeCount == 0) {
  806. MemoryRanges[0].BaseAddress = 0;
  807. MemoryRanges[0].Length = (1ull << PhysicalAddressBits);
  808. MemoryRanges[0].Type = DefaultType;
  809. *MemoryRangeCount = 1;
  810. return;
  811. }
  812. AllEndPointsCount = RawMemoryRangeCount << 1;
  813. AllEndPointsInclusive = calloc (AllEndPointsCount, sizeof (UINT64));
  814. AllRangePiecesCountMax = RawMemoryRangeCount * 3 + 1;
  815. AllRangePieces = calloc (AllRangePiecesCountMax, sizeof (MTRR_MEMORY_RANGE));
  816. CollectEndpoints (AllEndPointsInclusive, &AllEndPointsCount, RawMemoryRanges, RawMemoryRangeCount);
  817. for (Index = 0, AllRangePiecesCountActual = 0; Index < AllEndPointsCount - 1; Index++) {
  818. OverlapBitFlag1 = GetOverlapBitFlag (RawMemoryRanges, RawMemoryRangeCount, AllEndPointsInclusive[Index]);
  819. OverlapBitFlag2 = GetOverlapBitFlag (RawMemoryRanges, RawMemoryRangeCount, AllEndPointsInclusive[Index + 1]);
  820. OverlapFlagRelation = CheckOverlapBitFlagsRelation (OverlapBitFlag1, OverlapBitFlag2);
  821. switch (OverlapFlagRelation) {
  822. case 0: // [1, 2]
  823. AllRangePieces[AllRangePiecesCountActual].BaseAddress = AllEndPointsInclusive[Index];
  824. AllRangePieces[AllRangePiecesCountActual].Length = AllEndPointsInclusive[Index + 1] - AllEndPointsInclusive[Index] + 1;
  825. AllRangePiecesCountActual++;
  826. break;
  827. case 1: // [1, 2)
  828. AllRangePieces[AllRangePiecesCountActual].BaseAddress = AllEndPointsInclusive[Index];
  829. AllRangePieces[AllRangePiecesCountActual].Length = (AllEndPointsInclusive[Index + 1] - 1) - AllEndPointsInclusive[Index] + 1;
  830. AllRangePiecesCountActual++;
  831. break;
  832. case 2: // (1, 2]
  833. AllRangePieces[AllRangePiecesCountActual].BaseAddress = AllEndPointsInclusive[Index] + 1;
  834. AllRangePieces[AllRangePiecesCountActual].Length = AllEndPointsInclusive[Index + 1] - (AllEndPointsInclusive[Index] + 1) + 1;
  835. AllRangePiecesCountActual++;
  836. if (!IsEndpointInRanges (AllEndPointsInclusive[Index], AllRangePieces, AllRangePiecesCountActual)) {
  837. AllRangePieces[AllRangePiecesCountActual].BaseAddress = AllEndPointsInclusive[Index];
  838. AllRangePieces[AllRangePiecesCountActual].Length = 1;
  839. AllRangePiecesCountActual++;
  840. }
  841. break;
  842. case 3: // (1, 2)
  843. AllRangePieces[AllRangePiecesCountActual].BaseAddress = AllEndPointsInclusive[Index] + 1;
  844. AllRangePieces[AllRangePiecesCountActual].Length = (AllEndPointsInclusive[Index + 1] - 1) - (AllEndPointsInclusive[Index] + 1) + 1;
  845. if (AllRangePieces[AllRangePiecesCountActual].Length == 0) {
  846. // Only in case 3 can exists Length=0, we should skip such "segment".
  847. break;
  848. }
  849. AllRangePiecesCountActual++;
  850. if (!IsEndpointInRanges (AllEndPointsInclusive[Index], AllRangePieces, AllRangePiecesCountActual)) {
  851. AllRangePieces[AllRangePiecesCountActual].BaseAddress = AllEndPointsInclusive[Index];
  852. AllRangePieces[AllRangePiecesCountActual].Length = 1;
  853. AllRangePiecesCountActual++;
  854. }
  855. break;
  856. default:
  857. ASSERT (FALSE);
  858. }
  859. }
  860. for (Index = 0; Index < AllRangePiecesCountActual; Index++) {
  861. DetermineMemoryCacheType (DefaultType, &AllRangePieces[Index], RawMemoryRanges, RawMemoryRangeCount);
  862. }
  863. CompactAndExtendEffectiveMtrrMemoryRanges (DefaultType, PhysicalAddressBits, &AllRangePieces, &AllRangePiecesCountActual);
  864. ASSERT (*MemoryRangeCount >= AllRangePiecesCountActual);
  865. memcpy (MemoryRanges, AllRangePieces, AllRangePiecesCountActual * sizeof (MTRR_MEMORY_RANGE));
  866. *MemoryRangeCount = AllRangePiecesCountActual;
  867. free (AllEndPointsInclusive);
  868. free (AllRangePieces);
  869. }