5 Most of services in this library instance are suggested to be invoked by BSP only,
6 except for MtrrSetAllMtrrs() which is used to sync BSP's MTRR setting to APs.
8 Copyright (c) 2008 - 2017, Intel Corporation. All rights reserved.<BR>
9 This program and the accompanying materials
10 are licensed and made available under the terms and conditions of the BSD License
11 which accompanies this distribution. The full text of the license may be found at
12 http://opensource.org/licenses/bsd-license.php
14 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
15 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
20 #include <Register/Cpuid.h>
21 #include <Register/Msr.h>
23 #include <Library/MtrrLib.h>
24 #include <Library/BaseLib.h>
25 #include <Library/CpuLib.h>
26 #include <Library/BaseMemoryLib.h>
27 #include <Library/DebugLib.h>
29 #define OR_SEED 0x0101010101010101ull
30 #define CLEAR_SEED 0xFFFFFFFFFFFFFFFFull
31 #define MAX_WEIGHT MAX_UINT8
32 #define SCRATCH_BUFFER_SIZE (4 * SIZE_4KB)
33 #define MTRR_LIB_ASSERT_ALIGNED(B, L) ASSERT ((B & ~(L - 1)) == B);
35 #define M(x,y) ((x) * VectorCount + (y))
36 #define O(x,y) ((y) * VectorCount + (x))
39 // Context to save and restore when MTRRs are programmed
43 BOOLEAN InterruptState
;
53 // Temprary use for calculating the best MTRR settings.
61 // This table defines the offset, base and length of the fixed MTRRs
63 CONST FIXED_MTRR mMtrrLibFixedMtrrTable
[] = {
65 MSR_IA32_MTRR_FIX64K_00000
,
70 MSR_IA32_MTRR_FIX16K_80000
,
75 MSR_IA32_MTRR_FIX16K_A0000
,
80 MSR_IA32_MTRR_FIX4K_C0000
,
85 MSR_IA32_MTRR_FIX4K_C8000
,
90 MSR_IA32_MTRR_FIX4K_D0000
,
95 MSR_IA32_MTRR_FIX4K_D8000
,
100 MSR_IA32_MTRR_FIX4K_E0000
,
105 MSR_IA32_MTRR_FIX4K_E8000
,
110 MSR_IA32_MTRR_FIX4K_F0000
,
115 MSR_IA32_MTRR_FIX4K_F8000
,
122 // Lookup table used to print MTRRs
124 GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8
*mMtrrMemoryCacheTypeShortName
[] = {
125 "UC", // CacheUncacheable
126 "WC", // CacheWriteCombining
129 "WT", // CacheWriteThrough
130 "WP", // CacheWriteProtected
131 "WB", // CacheWriteBack
137 Worker function prints all MTRRs for debugging.
139 If MtrrSetting is not NULL, print MTRR settings from input MTRR
141 If MtrrSetting is NULL, print MTRR settings from MTRRs.
143 @param MtrrSetting A buffer holding all MTRRs content.
146 MtrrDebugPrintAllMtrrsWorker (
147 IN MTRR_SETTINGS
*MtrrSetting
151 Worker function returns the variable MTRR count for the CPU.
153 @return Variable MTRR count
157 GetVariableMtrrCountWorker (
161 MSR_IA32_MTRRCAP_REGISTER MtrrCap
;
163 MtrrCap
.Uint64
= AsmReadMsr64 (MSR_IA32_MTRRCAP
);
164 ASSERT (MtrrCap
.Bits
.VCNT
<= ARRAY_SIZE (((MTRR_VARIABLE_SETTINGS
*) 0)->Mtrr
));
165 return MtrrCap
.Bits
.VCNT
;
169 Returns the variable MTRR count for the CPU.
171 @return Variable MTRR count
176 GetVariableMtrrCount (
180 if (!IsMtrrSupported ()) {
183 return GetVariableMtrrCountWorker ();
187 Worker function returns the firmware usable variable MTRR count for the CPU.
189 @return Firmware usable variable MTRR count
193 GetFirmwareVariableMtrrCountWorker (
197 UINT32 VariableMtrrCount
;
198 UINT32 ReservedMtrrNumber
;
200 VariableMtrrCount
= GetVariableMtrrCountWorker ();
201 ReservedMtrrNumber
= PcdGet32 (PcdCpuNumberOfReservedVariableMtrrs
);
202 if (VariableMtrrCount
< ReservedMtrrNumber
) {
206 return VariableMtrrCount
- ReservedMtrrNumber
;
210 Returns the firmware usable variable MTRR count for the CPU.
212 @return Firmware usable variable MTRR count
217 GetFirmwareVariableMtrrCount (
221 if (!IsMtrrSupported ()) {
224 return GetFirmwareVariableMtrrCountWorker ();
228 Worker function returns the default MTRR cache type for the system.
230 If MtrrSetting is not NULL, returns the default MTRR cache type from input
231 MTRR settings buffer.
232 If MtrrSetting is NULL, returns the default MTRR cache type from MSR.
234 @param[in] MtrrSetting A buffer holding all MTRRs content.
236 @return The default MTRR cache type.
239 MTRR_MEMORY_CACHE_TYPE
240 MtrrGetDefaultMemoryTypeWorker (
241 IN MTRR_SETTINGS
*MtrrSetting
244 MSR_IA32_MTRR_DEF_TYPE_REGISTER DefType
;
246 if (MtrrSetting
== NULL
) {
247 DefType
.Uint64
= AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE
);
249 DefType
.Uint64
= MtrrSetting
->MtrrDefType
;
252 return (MTRR_MEMORY_CACHE_TYPE
) DefType
.Bits
.Type
;
257 Returns the default MTRR cache type for the system.
259 @return The default MTRR cache type.
262 MTRR_MEMORY_CACHE_TYPE
264 MtrrGetDefaultMemoryType (
268 if (!IsMtrrSupported ()) {
269 return CacheUncacheable
;
271 return MtrrGetDefaultMemoryTypeWorker (NULL
);
275 Preparation before programming MTRR.
277 This function will do some preparation for programming MTRRs:
278 disable cache, invalid cache and disable MTRR caching functionality
280 @param[out] MtrrContext Pointer to context to save
284 MtrrLibPreMtrrChange (
285 OUT MTRR_CONTEXT
*MtrrContext
288 MSR_IA32_MTRR_DEF_TYPE_REGISTER DefType
;
290 // Disable interrupts and save current interrupt state
292 MtrrContext
->InterruptState
= SaveAndDisableInterrupts();
295 // Enter no fill cache mode, CD=1(Bit30), NW=0 (Bit29)
300 // Save original CR4 value and clear PGE flag (Bit 7)
302 MtrrContext
->Cr4
= AsmReadCr4 ();
303 AsmWriteCr4 (MtrrContext
->Cr4
& (~BIT7
));
313 DefType
.Uint64
= AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE
);
315 AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE
, DefType
.Uint64
);
319 Cleaning up after programming MTRRs.
321 This function will do some clean up after programming MTRRs:
322 Flush all TLBs, re-enable caching, restore CR4.
324 @param[in] MtrrContext Pointer to context to restore
328 MtrrLibPostMtrrChangeEnableCache (
329 IN MTRR_CONTEXT
*MtrrContext
338 // Enable Normal Mode caching CD=NW=0, CD(Bit30), NW(Bit29)
343 // Restore original CR4 value
345 AsmWriteCr4 (MtrrContext
->Cr4
);
348 // Restore original interrupt state
350 SetInterruptState (MtrrContext
->InterruptState
);
354 Cleaning up after programming MTRRs.
356 This function will do some clean up after programming MTRRs:
357 enable MTRR caching functionality, and enable cache
359 @param[in] MtrrContext Pointer to context to restore
363 MtrrLibPostMtrrChange (
364 IN MTRR_CONTEXT
*MtrrContext
367 MSR_IA32_MTRR_DEF_TYPE_REGISTER DefType
;
371 DefType
.Uint64
= AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE
);
374 AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE
, DefType
.Uint64
);
376 MtrrLibPostMtrrChangeEnableCache (MtrrContext
);
380 Worker function gets the content in fixed MTRRs
382 @param[out] FixedSettings A buffer to hold fixed MTRRs content.
384 @retval The pointer of FixedSettings
388 MtrrGetFixedMtrrWorker (
389 OUT MTRR_FIXED_SETTINGS
*FixedSettings
394 for (Index
= 0; Index
< MTRR_NUMBER_OF_FIXED_MTRR
; Index
++) {
395 FixedSettings
->Mtrr
[Index
] =
396 AsmReadMsr64 (mMtrrLibFixedMtrrTable
[Index
].Msr
);
399 return FixedSettings
;
404 This function gets the content in fixed MTRRs
406 @param[out] FixedSettings A buffer to hold fixed MTRRs content.
408 @retval The pointer of FixedSettings
414 OUT MTRR_FIXED_SETTINGS
*FixedSettings
417 if (!IsMtrrSupported ()) {
418 return FixedSettings
;
421 return MtrrGetFixedMtrrWorker (FixedSettings
);
426 Worker function will get the raw value in variable MTRRs
428 If MtrrSetting is not NULL, gets the variable MTRRs raw value from input
429 MTRR settings buffer.
430 If MtrrSetting is NULL, gets the variable MTRRs raw value from MTRRs.
432 @param[in] MtrrSetting A buffer holding all MTRRs content.
433 @param[in] VariableMtrrCount Number of variable MTRRs.
434 @param[out] VariableSettings A buffer to hold variable MTRRs content.
436 @return The VariableSettings input pointer
439 MTRR_VARIABLE_SETTINGS
*
440 MtrrGetVariableMtrrWorker (
441 IN MTRR_SETTINGS
*MtrrSetting
,
442 IN UINT32 VariableMtrrCount
,
443 OUT MTRR_VARIABLE_SETTINGS
*VariableSettings
448 ASSERT (VariableMtrrCount
<= ARRAY_SIZE (VariableSettings
->Mtrr
));
450 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
451 if (MtrrSetting
== NULL
) {
452 VariableSettings
->Mtrr
[Index
].Mask
= AsmReadMsr64 (MSR_IA32_MTRR_PHYSMASK0
+ (Index
<< 1));
454 // Skip to read the Base MSR when the Mask.V is not set.
456 if (((MSR_IA32_MTRR_PHYSMASK_REGISTER
*)&VariableSettings
->Mtrr
[Index
].Mask
)->Bits
.V
!= 0) {
457 VariableSettings
->Mtrr
[Index
].Base
= AsmReadMsr64 (MSR_IA32_MTRR_PHYSBASE0
+ (Index
<< 1));
460 VariableSettings
->Mtrr
[Index
].Base
= MtrrSetting
->Variables
.Mtrr
[Index
].Base
;
461 VariableSettings
->Mtrr
[Index
].Mask
= MtrrSetting
->Variables
.Mtrr
[Index
].Mask
;
465 return VariableSettings
;
469 This function will get the raw value in variable MTRRs
471 @param[out] VariableSettings A buffer to hold variable MTRRs content.
473 @return The VariableSettings input pointer
476 MTRR_VARIABLE_SETTINGS
*
478 MtrrGetVariableMtrr (
479 OUT MTRR_VARIABLE_SETTINGS
*VariableSettings
482 if (!IsMtrrSupported ()) {
483 return VariableSettings
;
486 return MtrrGetVariableMtrrWorker (
488 GetVariableMtrrCountWorker (),
494 Programs fixed MTRRs registers.
496 @param[in] Type The memory type to set.
497 @param[in, out] Base The base address of memory range.
498 @param[in, out] Length The length of memory range.
499 @param[in, out] LastMsrIndex On input, the last index of the fixed MTRR MSR to program.
500 On return, the current index of the fixed MTRR MSR to program.
501 @param[out] ClearMask The bits to clear in the fixed MTRR MSR.
502 @param[out] OrMask The bits to set in the fixed MTRR MSR.
504 @retval RETURN_SUCCESS The cache type was updated successfully
505 @retval RETURN_UNSUPPORTED The requested range or cache type was invalid
510 MtrrLibProgramFixedMtrr (
511 IN MTRR_MEMORY_CACHE_TYPE Type
,
513 IN OUT UINT64
*Length
,
514 IN OUT UINT32
*LastMsrIndex
,
515 OUT UINT64
*ClearMask
,
520 UINT32 LeftByteShift
;
521 UINT32 RightByteShift
;
525 // Find the fixed MTRR index to be programmed
527 for (MsrIndex
= *LastMsrIndex
+ 1; MsrIndex
< ARRAY_SIZE (mMtrrLibFixedMtrrTable
); MsrIndex
++) {
528 if ((*Base
>= mMtrrLibFixedMtrrTable
[MsrIndex
].BaseAddress
) &&
531 mMtrrLibFixedMtrrTable
[MsrIndex
].BaseAddress
+
532 (8 * mMtrrLibFixedMtrrTable
[MsrIndex
].Length
)
540 ASSERT (MsrIndex
!= ARRAY_SIZE (mMtrrLibFixedMtrrTable
));
543 // Find the begin offset in fixed MTRR and calculate byte offset of left shift
545 if ((((UINT32
)*Base
- mMtrrLibFixedMtrrTable
[MsrIndex
].BaseAddress
) % mMtrrLibFixedMtrrTable
[MsrIndex
].Length
) != 0) {
547 // Base address should be aligned to the begin of a certain Fixed MTRR range.
549 return RETURN_UNSUPPORTED
;
551 LeftByteShift
= ((UINT32
)*Base
- mMtrrLibFixedMtrrTable
[MsrIndex
].BaseAddress
) / mMtrrLibFixedMtrrTable
[MsrIndex
].Length
;
552 ASSERT (LeftByteShift
< 8);
555 // Find the end offset in fixed MTRR and calculate byte offset of right shift
557 SubLength
= mMtrrLibFixedMtrrTable
[MsrIndex
].Length
* (8 - LeftByteShift
);
558 if (*Length
>= SubLength
) {
561 if (((UINT32
)(*Length
) % mMtrrLibFixedMtrrTable
[MsrIndex
].Length
) != 0) {
563 // Length should be aligned to the end of a certain Fixed MTRR range.
565 return RETURN_UNSUPPORTED
;
567 RightByteShift
= 8 - LeftByteShift
- (UINT32
)(*Length
) / mMtrrLibFixedMtrrTable
[MsrIndex
].Length
;
569 // Update SubLength by actual length
574 *ClearMask
= CLEAR_SEED
;
575 *OrMask
= MultU64x32 (OR_SEED
, (UINT32
) Type
);
577 if (LeftByteShift
!= 0) {
579 // Clear the low bits by LeftByteShift
581 *ClearMask
&= LShiftU64 (*ClearMask
, LeftByteShift
* 8);
582 *OrMask
&= LShiftU64 (*OrMask
, LeftByteShift
* 8);
585 if (RightByteShift
!= 0) {
587 // Clear the high bits by RightByteShift
589 *ClearMask
&= RShiftU64 (*ClearMask
, RightByteShift
* 8);
590 *OrMask
&= RShiftU64 (*OrMask
, RightByteShift
* 8);
593 *Length
-= SubLength
;
596 *LastMsrIndex
= MsrIndex
;
598 return RETURN_SUCCESS
;
603 Worker function gets the attribute of variable MTRRs.
605 This function shadows the content of variable MTRRs into an
606 internal array: VariableMtrr.
608 @param[in] VariableSettings The variable MTRR values to shadow
609 @param[in] VariableMtrrCount The number of variable MTRRs
610 @param[in] MtrrValidBitsMask The mask for the valid bit of the MTRR
611 @param[in] MtrrValidAddressMask The valid address mask for MTRR
612 @param[out] VariableMtrr The array to shadow variable MTRRs content
614 @return Number of MTRRs which has been used.
618 MtrrGetMemoryAttributeInVariableMtrrWorker (
619 IN MTRR_VARIABLE_SETTINGS
*VariableSettings
,
620 IN UINTN VariableMtrrCount
,
621 IN UINT64 MtrrValidBitsMask
,
622 IN UINT64 MtrrValidAddressMask
,
623 OUT VARIABLE_MTRR
*VariableMtrr
629 ZeroMem (VariableMtrr
, sizeof (VARIABLE_MTRR
) * ARRAY_SIZE (VariableSettings
->Mtrr
));
630 for (Index
= 0, UsedMtrr
= 0; Index
< VariableMtrrCount
; Index
++) {
631 if (((MSR_IA32_MTRR_PHYSMASK_REGISTER
*) &VariableSettings
->Mtrr
[Index
].Mask
)->Bits
.V
!= 0) {
632 VariableMtrr
[Index
].Msr
= (UINT32
)Index
;
633 VariableMtrr
[Index
].BaseAddress
= (VariableSettings
->Mtrr
[Index
].Base
& MtrrValidAddressMask
);
634 VariableMtrr
[Index
].Length
=
635 ((~(VariableSettings
->Mtrr
[Index
].Mask
& MtrrValidAddressMask
)) & MtrrValidBitsMask
) + 1;
636 VariableMtrr
[Index
].Type
= (VariableSettings
->Mtrr
[Index
].Base
& 0x0ff);
637 VariableMtrr
[Index
].Valid
= TRUE
;
638 VariableMtrr
[Index
].Used
= TRUE
;
646 Convert variable MTRRs to a RAW MTRR_MEMORY_RANGE array.
647 One MTRR_MEMORY_RANGE element is created for each MTRR setting.
648 The routine doesn't remove the overlap or combine the near-by region.
650 @param[in] VariableSettings The variable MTRR values to shadow
651 @param[in] VariableMtrrCount The number of variable MTRRs
652 @param[in] MtrrValidBitsMask The mask for the valid bit of the MTRR
653 @param[in] MtrrValidAddressMask The valid address mask for MTRR
654 @param[out] VariableMtrr The array to shadow variable MTRRs content
656 @return Number of MTRRs which has been used.
660 MtrrLibGetRawVariableRanges (
661 IN MTRR_VARIABLE_SETTINGS
*VariableSettings
,
662 IN UINTN VariableMtrrCount
,
663 IN UINT64 MtrrValidBitsMask
,
664 IN UINT64 MtrrValidAddressMask
,
665 OUT MTRR_MEMORY_RANGE
*VariableMtrr
671 ZeroMem (VariableMtrr
, sizeof (MTRR_MEMORY_RANGE
) * ARRAY_SIZE (VariableSettings
->Mtrr
));
672 for (Index
= 0, UsedMtrr
= 0; Index
< VariableMtrrCount
; Index
++) {
673 if (((MSR_IA32_MTRR_PHYSMASK_REGISTER
*) &VariableSettings
->Mtrr
[Index
].Mask
)->Bits
.V
!= 0) {
674 VariableMtrr
[Index
].BaseAddress
= (VariableSettings
->Mtrr
[Index
].Base
& MtrrValidAddressMask
);
675 VariableMtrr
[Index
].Length
=
676 ((~(VariableSettings
->Mtrr
[Index
].Mask
& MtrrValidAddressMask
)) & MtrrValidBitsMask
) + 1;
677 VariableMtrr
[Index
].Type
= (MTRR_MEMORY_CACHE_TYPE
)(VariableSettings
->Mtrr
[Index
].Base
& 0x0ff);
685 Gets the attribute of variable MTRRs.
687 This function shadows the content of variable MTRRs into an
688 internal array: VariableMtrr.
690 @param[in] MtrrValidBitsMask The mask for the valid bit of the MTRR
691 @param[in] MtrrValidAddressMask The valid address mask for MTRR
692 @param[out] VariableMtrr The array to shadow variable MTRRs content
694 @return The return value of this parameter indicates the
695 number of MTRRs which has been used.
700 MtrrGetMemoryAttributeInVariableMtrr (
701 IN UINT64 MtrrValidBitsMask
,
702 IN UINT64 MtrrValidAddressMask
,
703 OUT VARIABLE_MTRR
*VariableMtrr
706 MTRR_VARIABLE_SETTINGS VariableSettings
;
708 if (!IsMtrrSupported ()) {
712 MtrrGetVariableMtrrWorker (
714 GetVariableMtrrCountWorker (),
718 return MtrrGetMemoryAttributeInVariableMtrrWorker (
720 GetFirmwareVariableMtrrCountWorker (),
722 MtrrValidAddressMask
,
728 Return the biggest alignment (lowest set bit) of address.
729 The function is equivalent to: 1 << LowBitSet64 (Address).
731 @param Address The address to return the alignment.
732 @param Alignment0 The alignment to return when Address is 0.
734 @return The least alignment of the Address.
737 MtrrLibBiggestAlignment (
746 return Address
& ((~Address
) + 1);
750 Return whether the left MTRR type precedes the right MTRR type.
752 The MTRR type precedence rules are:
753 1. UC precedes any other type
755 For further details, please refer the IA32 Software Developer's Manual,
756 Volume 3, Section "MTRR Precedences".
758 @param Left The left MTRR type.
759 @param Right The right MTRR type.
761 @retval TRUE Left precedes Right.
762 @retval FALSE Left doesn't precede Right.
765 MtrrLibTypeLeftPrecedeRight (
766 IN MTRR_MEMORY_CACHE_TYPE Left
,
767 IN MTRR_MEMORY_CACHE_TYPE Right
770 return (BOOLEAN
) (Left
== CacheUncacheable
|| (Left
== CacheWriteThrough
&& Right
== CacheWriteBack
));
774 Initializes the valid bits mask and valid address mask for MTRRs.
776 This function initializes the valid bits mask and valid address mask for MTRRs.
778 @param[out] MtrrValidBitsMask The mask for the valid bit of the MTRR
779 @param[out] MtrrValidAddressMask The valid address mask for the MTRR
783 MtrrLibInitializeMtrrMask (
784 OUT UINT64
*MtrrValidBitsMask
,
785 OUT UINT64
*MtrrValidAddressMask
788 UINT32 MaxExtendedFunction
;
789 CPUID_VIR_PHY_ADDRESS_SIZE_EAX VirPhyAddressSize
;
792 AsmCpuid (CPUID_EXTENDED_FUNCTION
, &MaxExtendedFunction
, NULL
, NULL
, NULL
);
794 if (MaxExtendedFunction
>= CPUID_VIR_PHY_ADDRESS_SIZE
) {
795 AsmCpuid (CPUID_VIR_PHY_ADDRESS_SIZE
, &VirPhyAddressSize
.Uint32
, NULL
, NULL
, NULL
);
797 VirPhyAddressSize
.Bits
.PhysicalAddressBits
= 36;
800 *MtrrValidBitsMask
= LShiftU64 (1, VirPhyAddressSize
.Bits
.PhysicalAddressBits
) - 1;
801 *MtrrValidAddressMask
= *MtrrValidBitsMask
& 0xfffffffffffff000ULL
;
806 Determines the real attribute of a memory range.
808 This function is to arbitrate the real attribute of the memory when
809 there are 2 MTRRs covers the same memory range. For further details,
810 please refer the IA32 Software Developer's Manual, Volume 3,
811 Section "MTRR Precedences".
813 @param[in] MtrrType1 The first kind of Memory type
814 @param[in] MtrrType2 The second kind of memory type
817 MTRR_MEMORY_CACHE_TYPE
819 IN MTRR_MEMORY_CACHE_TYPE MtrrType1
,
820 IN MTRR_MEMORY_CACHE_TYPE MtrrType2
823 if (MtrrType1
== MtrrType2
) {
828 MtrrLibTypeLeftPrecedeRight (MtrrType1
, MtrrType2
) ||
829 MtrrLibTypeLeftPrecedeRight (MtrrType2
, MtrrType1
)
832 if (MtrrLibTypeLeftPrecedeRight (MtrrType1
, MtrrType2
)) {
840 Worker function will get the memory cache type of the specific address.
842 If MtrrSetting is not NULL, gets the memory cache type from input
843 MTRR settings buffer.
844 If MtrrSetting is NULL, gets the memory cache type from MTRRs.
846 @param[in] MtrrSetting A buffer holding all MTRRs content.
847 @param[in] Address The specific address
849 @return Memory cache type of the specific address
852 MTRR_MEMORY_CACHE_TYPE
853 MtrrGetMemoryAttributeByAddressWorker (
854 IN MTRR_SETTINGS
*MtrrSetting
,
855 IN PHYSICAL_ADDRESS Address
858 MSR_IA32_MTRR_DEF_TYPE_REGISTER DefType
;
862 MTRR_MEMORY_CACHE_TYPE MtrrType
;
863 MTRR_MEMORY_RANGE VariableMtrr
[ARRAY_SIZE (MtrrSetting
->Variables
.Mtrr
)];
864 UINT64 MtrrValidBitsMask
;
865 UINT64 MtrrValidAddressMask
;
866 UINT32 VariableMtrrCount
;
867 MTRR_VARIABLE_SETTINGS VariableSettings
;
870 // Check if MTRR is enabled, if not, return UC as attribute
872 if (MtrrSetting
== NULL
) {
873 DefType
.Uint64
= AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE
);
875 DefType
.Uint64
= MtrrSetting
->MtrrDefType
;
878 if (DefType
.Bits
.E
== 0) {
879 return CacheUncacheable
;
883 // If address is less than 1M, then try to go through the fixed MTRR
885 if (Address
< BASE_1MB
) {
886 if (DefType
.Bits
.FE
!= 0) {
888 // Go through the fixed MTRR
890 for (Index
= 0; Index
< MTRR_NUMBER_OF_FIXED_MTRR
; Index
++) {
891 if (Address
>= mMtrrLibFixedMtrrTable
[Index
].BaseAddress
&&
892 Address
< mMtrrLibFixedMtrrTable
[Index
].BaseAddress
+
893 (mMtrrLibFixedMtrrTable
[Index
].Length
* 8)) {
895 ((UINTN
) Address
- mMtrrLibFixedMtrrTable
[Index
].BaseAddress
) /
896 mMtrrLibFixedMtrrTable
[Index
].Length
;
897 if (MtrrSetting
== NULL
) {
898 FixedMtrr
= AsmReadMsr64 (mMtrrLibFixedMtrrTable
[Index
].Msr
);
900 FixedMtrr
= MtrrSetting
->Fixed
.Mtrr
[Index
];
902 return (MTRR_MEMORY_CACHE_TYPE
) (RShiftU64 (FixedMtrr
, SubIndex
* 8) & 0xFF);
908 VariableMtrrCount
= GetVariableMtrrCountWorker ();
909 ASSERT (VariableMtrrCount
<= ARRAY_SIZE (MtrrSetting
->Variables
.Mtrr
));
910 MtrrGetVariableMtrrWorker (MtrrSetting
, VariableMtrrCount
, &VariableSettings
);
912 MtrrLibInitializeMtrrMask (&MtrrValidBitsMask
, &MtrrValidAddressMask
);
913 MtrrLibGetRawVariableRanges (
917 MtrrValidAddressMask
,
922 // Go through the variable MTRR
924 MtrrType
= CacheInvalid
;
925 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
926 if (VariableMtrr
[Index
].Length
!= 0) {
927 if (Address
>= VariableMtrr
[Index
].BaseAddress
&&
928 Address
< VariableMtrr
[Index
].BaseAddress
+ VariableMtrr
[Index
].Length
) {
929 if (MtrrType
== CacheInvalid
) {
930 MtrrType
= (MTRR_MEMORY_CACHE_TYPE
) VariableMtrr
[Index
].Type
;
932 MtrrType
= MtrrLibPrecedence (MtrrType
, (MTRR_MEMORY_CACHE_TYPE
) VariableMtrr
[Index
].Type
);
939 // If there is no MTRR which covers the Address, use the default MTRR type.
941 if (MtrrType
== CacheInvalid
) {
942 MtrrType
= (MTRR_MEMORY_CACHE_TYPE
) DefType
.Bits
.Type
;
950 This function will get the memory cache type of the specific address.
952 This function is mainly for debug purpose.
954 @param[in] Address The specific address
956 @return Memory cache type of the specific address
959 MTRR_MEMORY_CACHE_TYPE
961 MtrrGetMemoryAttribute (
962 IN PHYSICAL_ADDRESS Address
965 if (!IsMtrrSupported ()) {
966 return CacheUncacheable
;
969 return MtrrGetMemoryAttributeByAddressWorker (NULL
, Address
);
973 Update the Ranges array to change the specified range identified by
974 BaseAddress and Length to Type.
976 @param Ranges Array holding memory type settings for all memory regions.
977 @param Capacity The maximum count of memory ranges the array can hold.
978 @param Count Return the new memory range count in the array.
979 @param BaseAddress The base address of the memory range to change type.
980 @param Length The length of the memory range to change type.
981 @param Type The new type of the specified memory range.
983 @retval RETURN_SUCCESS The type of the specified memory range is
984 changed successfully.
985 @retval RETURN_ALREADY_STARTED The type of the specified memory range equals
987 @retval RETURN_OUT_OF_RESOURCES The new type set causes the count of memory
988 range exceeds capacity.
991 MtrrLibSetMemoryType (
992 IN MTRR_MEMORY_RANGE
*Ranges
,
995 IN UINT64 BaseAddress
,
997 IN MTRR_MEMORY_CACHE_TYPE Type
1010 Limit
= BaseAddress
+ Length
;
1011 StartIndex
= *Count
;
1013 for (Index
= 0; Index
< *Count
; Index
++) {
1014 if ((StartIndex
== *Count
) &&
1015 (Ranges
[Index
].BaseAddress
<= BaseAddress
) &&
1016 (BaseAddress
< Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
)) {
1018 LengthLeft
= BaseAddress
- Ranges
[Index
].BaseAddress
;
1021 if ((EndIndex
== *Count
) &&
1022 (Ranges
[Index
].BaseAddress
< Limit
) &&
1023 (Limit
<= Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
)) {
1025 LengthRight
= Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
- Limit
;
1030 ASSERT (StartIndex
!= *Count
&& EndIndex
!= *Count
);
1031 if (StartIndex
== EndIndex
&& Ranges
[StartIndex
].Type
== Type
) {
1032 return RETURN_ALREADY_STARTED
;
1036 // The type change may cause merging with previous range or next range.
1037 // Update the StartIndex, EndIndex, BaseAddress, Length so that following
1038 // logic doesn't need to consider merging.
1040 if (StartIndex
!= 0) {
1041 if (LengthLeft
== 0 && Ranges
[StartIndex
- 1].Type
== Type
) {
1043 Length
+= Ranges
[StartIndex
].Length
;
1044 BaseAddress
-= Ranges
[StartIndex
].Length
;
1047 if (EndIndex
!= (*Count
) - 1) {
1048 if (LengthRight
== 0 && Ranges
[EndIndex
+ 1].Type
== Type
) {
1050 Length
+= Ranges
[EndIndex
].Length
;
1055 // |- 0 -|- 1 -|- 2 -|- 3 -| StartIndex EndIndex DeltaCount Count (Count = 4)
1056 // |++++++++++++++++++| 0 3 1=3-0-2 3
1057 // |+++++++| 0 1 -1=1-0-2 5
1058 // |+| 0 0 -2=0-0-2 6
1059 // |+++| 0 0 -1=0-0-2+1 5
1062 DeltaCount
= EndIndex
- StartIndex
- 2;
1063 if (LengthLeft
== 0) {
1066 if (LengthRight
== 0) {
1069 if (*Count
- DeltaCount
> Capacity
) {
1070 return RETURN_OUT_OF_RESOURCES
;
1074 // Reserve (-DeltaCount) space
1076 CopyMem (&Ranges
[EndIndex
+ 1 - DeltaCount
], &Ranges
[EndIndex
+ 1], (*Count
- EndIndex
- 1) * sizeof (Ranges
[0]));
1077 *Count
-= DeltaCount
;
1079 if (LengthLeft
!= 0) {
1080 Ranges
[StartIndex
].Length
= LengthLeft
;
1083 if (LengthRight
!= 0) {
1084 Ranges
[EndIndex
- DeltaCount
].BaseAddress
= BaseAddress
+ Length
;
1085 Ranges
[EndIndex
- DeltaCount
].Length
= LengthRight
;
1086 Ranges
[EndIndex
- DeltaCount
].Type
= Ranges
[EndIndex
].Type
;
1088 Ranges
[StartIndex
].BaseAddress
= BaseAddress
;
1089 Ranges
[StartIndex
].Length
= Length
;
1090 Ranges
[StartIndex
].Type
= Type
;
1091 return RETURN_SUCCESS
;
1095 Return the number of memory types in range [BaseAddress, BaseAddress + Length).
1097 @param Ranges Array holding memory type settings for all memory regions.
1098 @param RangeCount The count of memory ranges the array holds.
1099 @param BaseAddress Base address.
1100 @param Length Length.
1101 @param Types Return bit mask to indicate all memory types in the specified range.
1103 @retval Number of memory types.
1106 MtrrLibGetNumberOfTypes (
1107 IN CONST MTRR_MEMORY_RANGE
*Ranges
,
1108 IN UINTN RangeCount
,
1109 IN UINT64 BaseAddress
,
1111 IN OUT UINT8
*Types OPTIONAL
1120 for (Index
= 0; Index
< RangeCount
; Index
++) {
1121 if ((Ranges
[Index
].BaseAddress
<= BaseAddress
) &&
1122 (BaseAddress
< Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
)
1124 if ((LocalTypes
& (1 << Ranges
[Index
].Type
)) == 0) {
1125 LocalTypes
|= (UINT8
)(1 << Ranges
[Index
].Type
);
1129 if (BaseAddress
+ Length
> Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
) {
1130 Length
-= Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
- BaseAddress
;
1131 BaseAddress
= Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
;
1138 if (Types
!= NULL
) {
1139 *Types
= LocalTypes
;
1145 Calculate the least MTRR number from vector Start to Stop and update
1146 the Previous of all vectors from Start to Stop is updated to reflect
1147 how the memory range is covered by MTRR.
1149 @param VectorCount The count of vectors in the graph.
1150 @param Vector Array holding all vectors.
1151 @param Weight 2-dimention array holding weights between vectors.
1152 @param Start Start vector.
1153 @param Stop Stop vector.
1154 @param IncludeOptional TRUE to count the optional weight.
1157 MtrrLibCalculateLeastMtrrs (
1158 IN UINT16 VectorCount
,
1159 IN MTRR_LIB_ADDRESS
*Vector
,
1160 IN OUT CONST UINT8
*Weight
,
1163 IN BOOLEAN IncludeOptional
1172 for (Index
= Start
; Index
<= Stop
; Index
++) {
1173 Vector
[Index
].Visited
= FALSE
;
1174 Vector
[Index
].Previous
= VectorCount
;
1175 Mandatory
= Weight
[M(Start
,Index
)];
1176 Vector
[Index
].Weight
= Mandatory
;
1177 if (Mandatory
!= MAX_WEIGHT
) {
1178 Optional
= IncludeOptional
? Weight
[O(Start
, Index
)] : 0;
1179 Vector
[Index
].Weight
+= Optional
;
1180 ASSERT (Vector
[Index
].Weight
>= Optional
);
1186 while (!Vector
[Stop
].Visited
) {
1188 // Update the weight from the shortest vector to other unvisited vectors
1190 for (Index
= Start
+ 1; Index
<= Stop
; Index
++) {
1191 if (!Vector
[Index
].Visited
) {
1192 Mandatory
= Weight
[M(MinI
, Index
)];
1193 if (Mandatory
!= MAX_WEIGHT
) {
1194 Optional
= IncludeOptional
? Weight
[O(MinI
, Index
)] : 0;
1195 if (MinWeight
+ Mandatory
+ Optional
<= Vector
[Index
].Weight
) {
1196 Vector
[Index
].Weight
= MinWeight
+ Mandatory
+ Optional
;
1197 Vector
[Index
].Previous
= MinI
; // Previous is Start based.
1204 // Find the shortest vector from Start
1207 MinWeight
= MAX_WEIGHT
;
1208 for (Index
= Start
+ 1; Index
<= Stop
; Index
++) {
1209 if (!Vector
[Index
].Visited
&& MinWeight
> Vector
[Index
].Weight
) {
1211 MinWeight
= Vector
[Index
].Weight
;
1216 // Mark the shortest vector from Start as visited
1218 Vector
[MinI
].Visited
= TRUE
;
1223 Append the MTRR setting to MTRR setting array.
1225 @param Mtrrs Array holding all MTRR settings.
1226 @param MtrrCapacity Capacity of the MTRR array.
1227 @param MtrrCount The count of MTRR settings in array.
1228 @param BaseAddress Base address.
1229 @param Length Length.
1230 @param Type Memory type.
1232 @retval RETURN_SUCCESS MTRR setting is appended to array.
1233 @retval RETURN_OUT_OF_RESOURCES Array is full.
1236 MtrrLibAppendVariableMtrr (
1237 IN OUT MTRR_MEMORY_RANGE
*Mtrrs
,
1238 IN UINT32 MtrrCapacity
,
1239 IN OUT UINT32
*MtrrCount
,
1240 IN UINT64 BaseAddress
,
1242 IN MTRR_MEMORY_CACHE_TYPE Type
1245 if (*MtrrCount
== MtrrCapacity
) {
1246 return RETURN_OUT_OF_RESOURCES
;
1249 Mtrrs
[*MtrrCount
].BaseAddress
= BaseAddress
;
1250 Mtrrs
[*MtrrCount
].Length
= Length
;
1251 Mtrrs
[*MtrrCount
].Type
= Type
;
1253 return RETURN_SUCCESS
;
1257 Return the memory type that has the least precedence.
1259 @param TypeBits Bit mask of memory type.
1261 @retval Memory type that has the least precedence.
1263 MTRR_MEMORY_CACHE_TYPE
1270 ASSERT (TypeBits
!= 0);
1271 for (Type
= 7; (INT8
)TypeBits
> 0; Type
--, TypeBits
<<= 1);
1272 return (MTRR_MEMORY_CACHE_TYPE
)Type
;
1276 Return TRUE when the Operand is exactly power of 2.
1278 @retval TRUE Operand is exactly power of 2.
1279 @retval FALSE Operand is not power of 2.
1282 MtrrLibIsPowerOfTwo (
1286 ASSERT (Operand
!= 0);
1287 return (BOOLEAN
) ((Operand
& (Operand
- 1)) == 0);
1291 Calculate the subtractive path from vector Start to Stop.
1293 @param DefaultType Default memory type.
1294 @param A0 Alignment to use when base address is 0.
1295 @param Ranges Array holding memory type settings for all memory regions.
1296 @param RangeCount The count of memory ranges the array holds.
1297 @param VectorCount The count of vectors in the graph.
1298 @param Vector Array holding all vectors.
1299 @param Weight 2-dimention array holding weights between vectors.
1300 @param Start Start vector.
1301 @param Stop Stop vector.
1302 @param Types Type bit mask of memory range from Start to Stop.
1303 @param TypeCount Number of different memory types from Start to Stop.
1304 @param Mtrrs Array holding all MTRR settings.
1305 @param MtrrCapacity Capacity of the MTRR array.
1306 @param MtrrCount The count of MTRR settings in array.
1308 @retval RETURN_SUCCESS The subtractive path is calculated successfully.
1309 @retval RETURN_OUT_OF_RESOURCES The MTRR setting array is full.
1313 MtrrLibCalculateSubtractivePath (
1314 IN MTRR_MEMORY_CACHE_TYPE DefaultType
,
1316 IN CONST MTRR_MEMORY_RANGE
*Ranges
,
1317 IN UINTN RangeCount
,
1318 IN UINT16 VectorCount
,
1319 IN MTRR_LIB_ADDRESS
*Vector
,
1320 IN OUT UINT8
*Weight
,
1325 IN OUT MTRR_MEMORY_RANGE
*Mtrrs
, OPTIONAL
1326 IN UINT32 MtrrCapacity
, OPTIONAL
1327 IN OUT UINT32
*MtrrCount OPTIONAL
1330 RETURN_STATUS Status
;
1333 UINT8 PrecedentTypes
;
1342 MTRR_MEMORY_CACHE_TYPE LowestType
;
1343 MTRR_MEMORY_CACHE_TYPE LowestPrecedentType
;
1345 Base
= Vector
[Start
].Address
;
1346 Length
= Vector
[Stop
].Address
- Base
;
1348 LowestType
= MtrrLibLowestType (Types
);
1351 // Clear the lowest type (highest bit) to get the precedent types
1353 PrecedentTypes
= ~(1 << LowestType
) & Types
;
1354 LowestPrecedentType
= MtrrLibLowestType (PrecedentTypes
);
1356 if (Mtrrs
== NULL
) {
1357 Weight
[M(Start
, Stop
)] = ((LowestType
== DefaultType
) ? 0 : 1);
1358 Weight
[O(Start
, Stop
)] = ((LowestType
== DefaultType
) ? 1 : 0);
1361 // Add all high level ranges
1364 for (Index
= 0; Index
< RangeCount
; Index
++) {
1368 if ((Base
< Ranges
[Index
].BaseAddress
) || (Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
<= Base
)) {
1373 // Base is in the Range[Index]
1375 if (Base
+ Length
> Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
) {
1376 SubLength
= Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
- Base
;
1380 if (((1 << Ranges
[Index
].Type
) & PrecedentTypes
) != 0) {
1382 // Meet a range whose types take precedence.
1383 // Update the [HBase, HBase + HLength) to include the range,
1384 // [HBase, HBase + HLength) may contain sub ranges with 2 different types, and both take precedence.
1386 if (HBase
== MAX_UINT64
) {
1389 HLength
+= SubLength
;
1393 Length
-= SubLength
;
1399 if ((Ranges
[Index
].Type
== LowestType
) || (Length
== 0)) { // meet low type or end
1402 // Add the MTRRs for each high priority type range
1403 // the range[HBase, HBase + HLength) contains only two types.
1404 // We might use positive or subtractive, depending on which way uses less MTRR
1406 for (SubStart
= Start
; SubStart
<= Stop
; SubStart
++) {
1407 if (Vector
[SubStart
].Address
== HBase
) {
1412 for (SubStop
= SubStart
; SubStop
<= Stop
; SubStop
++) {
1413 if (Vector
[SubStop
].Address
== HBase
+ HLength
) {
1417 ASSERT (Vector
[SubStart
].Address
== HBase
);
1418 ASSERT (Vector
[SubStop
].Address
== HBase
+ HLength
);
1420 if ((TypeCount
== 2) || (SubStart
== SubStop
- 1)) {
1422 // add subtractive MTRRs for [HBase, HBase + HLength)
1423 // [HBase, HBase + HLength) contains only one type.
1424 // while - loop is to split the range to MTRR - compliant aligned range.
1426 if (Mtrrs
== NULL
) {
1427 Weight
[M (Start
, Stop
)] += (UINT8
)(SubStop
- SubStart
);
1429 while (SubStart
!= SubStop
) {
1430 Status
= MtrrLibAppendVariableMtrr (
1431 Mtrrs
, MtrrCapacity
, MtrrCount
,
1432 Vector
[SubStart
].Address
, Vector
[SubStart
].Length
, (MTRR_MEMORY_CACHE_TYPE
) Vector
[SubStart
].Type
1434 if (RETURN_ERROR (Status
)) {
1441 ASSERT (TypeCount
== 3);
1442 MtrrLibCalculateLeastMtrrs (VectorCount
, Vector
, Weight
, SubStart
, SubStop
, TRUE
);
1444 if (Mtrrs
== NULL
) {
1445 Weight
[M (Start
, Stop
)] += Vector
[SubStop
].Weight
;
1447 // When we need to collect the optimal path from SubStart to SubStop
1448 while (SubStop
!= SubStart
) {
1450 Pre
= Vector
[Cur
].Previous
;
1453 if (Weight
[M (Pre
, Cur
)] != 0) {
1454 Status
= MtrrLibAppendVariableMtrr (
1455 Mtrrs
, MtrrCapacity
, MtrrCount
,
1456 Vector
[Pre
].Address
, Vector
[Cur
].Address
- Vector
[Pre
].Address
, LowestPrecedentType
1458 if (RETURN_ERROR (Status
)) {
1462 if (Pre
!= Cur
- 1) {
1463 Status
= MtrrLibCalculateSubtractivePath (
1466 VectorCount
, Vector
, Weight
,
1467 Pre
, Cur
, PrecedentTypes
, 2,
1468 Mtrrs
, MtrrCapacity
, MtrrCount
1470 if (RETURN_ERROR (Status
)) {
1479 // Reset HBase, HLength
1485 return RETURN_SUCCESS
;
1489 Calculate MTRR settings to cover the specified memory ranges.
1491 @param DefaultType Default memory type.
1492 @param A0 Alignment to use when base address is 0.
1493 @param Ranges Memory range array holding the memory type
1494 settings for all memory address.
1495 @param RangeCount Count of memory ranges.
1496 @param Scratch A temporary scratch buffer that is used to perform the calculation.
1497 This is an optional parameter that may be NULL.
1498 @param ScratchSize Pointer to the size in bytes of the scratch buffer.
1499 It may be updated to the actual required size when the calculation
1500 needs more scratch buffer.
1501 @param Mtrrs Array holding all MTRR settings.
1502 @param MtrrCapacity Capacity of the MTRR array.
1503 @param MtrrCount The count of MTRR settings in array.
1505 @retval RETURN_SUCCESS Variable MTRRs are allocated successfully.
1506 @retval RETURN_OUT_OF_RESOURCES Count of variable MTRRs exceeds capacity.
1507 @retval RETURN_BUFFER_TOO_SMALL The scratch buffer is too small for MTRR calculation.
1510 MtrrLibCalculateMtrrs (
1511 IN MTRR_MEMORY_CACHE_TYPE DefaultType
,
1513 IN CONST MTRR_MEMORY_RANGE
*Ranges
,
1514 IN UINTN RangeCount
,
1516 IN OUT UINTN
*ScratchSize
,
1517 IN OUT MTRR_MEMORY_RANGE
*Mtrrs
,
1518 IN UINT32 MtrrCapacity
,
1519 IN OUT UINT32
*MtrrCount
1529 MTRR_LIB_ADDRESS
*Vector
;
1533 UINTN RequiredScratchSize
;
1538 RETURN_STATUS Status
;
1540 Base0
= Ranges
[0].BaseAddress
;
1541 Base1
= Ranges
[RangeCount
- 1].BaseAddress
+ Ranges
[RangeCount
- 1].Length
;
1542 MTRR_LIB_ASSERT_ALIGNED (Base0
, Base1
- Base0
);
1545 // Count the number of vectors.
1547 Vector
= (MTRR_LIB_ADDRESS
*)Scratch
;
1548 for (VectorIndex
= 0, Index
= 0; Index
< RangeCount
; Index
++) {
1549 Base
= Ranges
[Index
].BaseAddress
;
1550 Length
= Ranges
[Index
].Length
;
1551 while (Length
!= 0) {
1552 Alignment
= MtrrLibBiggestAlignment (Base
, A0
);
1553 SubLength
= Alignment
;
1554 if (SubLength
> Length
) {
1555 SubLength
= GetPowerOfTwo64 (Length
);
1557 if (VectorIndex
< *ScratchSize
/ sizeof (*Vector
)) {
1558 Vector
[VectorIndex
].Address
= Base
;
1559 Vector
[VectorIndex
].Alignment
= Alignment
;
1560 Vector
[VectorIndex
].Type
= Ranges
[Index
].Type
;
1561 Vector
[VectorIndex
].Length
= SubLength
;
1564 Length
-= SubLength
;
1569 // Vector[VectorIndex] = Base1, so whole vector count is (VectorIndex + 1).
1571 VectorCount
= VectorIndex
+ 1;
1573 DEBUG_CACHE
, "VectorCount (%016lx - %016lx) = %d\n",
1574 Ranges
[0].BaseAddress
, Ranges
[RangeCount
- 1].BaseAddress
+ Ranges
[RangeCount
- 1].Length
, VectorCount
1576 ASSERT (VectorCount
< MAX_UINT16
);
1578 RequiredScratchSize
= VectorCount
* sizeof (*Vector
) + VectorCount
* VectorCount
* sizeof (*Weight
);
1579 if (*ScratchSize
< RequiredScratchSize
) {
1580 *ScratchSize
= RequiredScratchSize
;
1581 return RETURN_BUFFER_TOO_SMALL
;
1583 Vector
[VectorCount
- 1].Address
= Base1
;
1585 Weight
= (UINT8
*) &Vector
[VectorCount
];
1587 // Set mandatory weight between any vector to max
1588 // Set optional weight and between any vector and self->self to 0
1595 for (VectorIndex
= 0; VectorIndex
< VectorCount
; VectorIndex
++) {
1596 SetMem (&Weight
[M(VectorIndex
, 0)], VectorIndex
+ 1, 0);
1597 if (VectorIndex
!= VectorCount
- 1) {
1598 Weight
[M (VectorIndex
, VectorIndex
+ 1)] = (DefaultType
== Vector
[VectorIndex
].Type
) ? 0 : 1;
1599 SetMem (&Weight
[M (VectorIndex
, VectorIndex
+ 2)], VectorCount
- VectorIndex
- 2, MAX_WEIGHT
);
1603 for (TypeCount
= 2; TypeCount
<= 3; TypeCount
++) {
1604 for (Start
= 0; Start
< VectorCount
; Start
++) {
1605 for (Stop
= Start
+ 2; Stop
< VectorCount
; Stop
++) {
1606 ASSERT (Vector
[Stop
].Address
> Vector
[Start
].Address
);
1607 Length
= Vector
[Stop
].Address
- Vector
[Start
].Address
;
1608 if (Length
> Vector
[Start
].Alignment
) {
1610 // Pickup a new Start when [Start, Stop) cannot be described by one MTRR.
1614 if ((Weight
[M(Start
, Stop
)] == MAX_WEIGHT
) && MtrrLibIsPowerOfTwo (Length
)) {
1615 if (MtrrLibGetNumberOfTypes (
1616 Ranges
, RangeCount
, Vector
[Start
].Address
, Vector
[Stop
].Address
- Vector
[Start
].Address
, &Type
1619 // Update the Weight[Start, Stop] using subtractive path.
1621 MtrrLibCalculateSubtractivePath (
1624 (UINT16
)VectorCount
, Vector
, Weight
,
1625 Start
, Stop
, Type
, TypeCount
,
1628 } else if (TypeCount
== 2) {
1630 // Pick up a new Start when we expect 2-type range, but 3-type range is met.
1631 // Because no matter how Stop is increased, we always meet 3-type range.
1640 Status
= RETURN_SUCCESS
;
1641 MtrrLibCalculateLeastMtrrs ((UINT16
) VectorCount
, Vector
, Weight
, 0, (UINT16
) VectorCount
- 1, FALSE
);
1642 Stop
= (UINT16
) VectorCount
- 1;
1644 Start
= Vector
[Stop
].Previous
;
1645 TypeCount
= MAX_UINT8
;
1647 if (Weight
[M(Start
, Stop
)] != 0) {
1648 TypeCount
= MtrrLibGetNumberOfTypes (Ranges
, RangeCount
, Vector
[Start
].Address
, Vector
[Stop
].Address
- Vector
[Start
].Address
, &Type
);
1649 Status
= MtrrLibAppendVariableMtrr (
1650 Mtrrs
, MtrrCapacity
, MtrrCount
,
1651 Vector
[Start
].Address
, Vector
[Stop
].Address
- Vector
[Start
].Address
,
1652 MtrrLibLowestType (Type
)
1654 if (RETURN_ERROR (Status
)) {
1659 if (Start
!= Stop
- 1) {
1661 // substractive path
1663 if (TypeCount
== MAX_UINT8
) {
1664 TypeCount
= MtrrLibGetNumberOfTypes (
1665 Ranges
, RangeCount
, Vector
[Start
].Address
, Vector
[Stop
].Address
- Vector
[Start
].Address
, &Type
1668 Status
= MtrrLibCalculateSubtractivePath (
1671 (UINT16
) VectorCount
, Vector
, Weight
, Start
, Stop
,
1673 Mtrrs
, MtrrCapacity
, MtrrCount
1675 if (RETURN_ERROR (Status
)) {
1686 Apply the fixed MTRR settings to memory range array.
1688 @param Fixed The fixed MTRR settings.
1689 @param Ranges Return the memory range array holding memory type
1690 settings for all memory address.
1691 @param RangeCapacity The capacity of memory range array.
1692 @param RangeCount Return the count of memory range.
1694 @retval RETURN_SUCCESS The memory range array is returned successfully.
1695 @retval RETURN_OUT_OF_RESOURCES The count of memory ranges exceeds capacity.
1698 MtrrLibApplyFixedMtrrs (
1699 IN MTRR_FIXED_SETTINGS
*Fixed
,
1700 IN OUT MTRR_MEMORY_RANGE
*Ranges
,
1701 IN UINTN RangeCapacity
,
1702 IN OUT UINTN
*RangeCount
1705 RETURN_STATUS Status
;
1708 MTRR_MEMORY_CACHE_TYPE MemoryType
;
1712 for (MsrIndex
= 0; MsrIndex
< ARRAY_SIZE (mMtrrLibFixedMtrrTable
); MsrIndex
++) {
1713 ASSERT (Base
== mMtrrLibFixedMtrrTable
[MsrIndex
].BaseAddress
);
1714 for (Index
= 0; Index
< sizeof (UINT64
); Index
++) {
1715 MemoryType
= (MTRR_MEMORY_CACHE_TYPE
)((UINT8
*)(&Fixed
->Mtrr
[MsrIndex
]))[Index
];
1716 Status
= MtrrLibSetMemoryType (
1717 Ranges
, RangeCapacity
, RangeCount
, Base
, mMtrrLibFixedMtrrTable
[MsrIndex
].Length
, MemoryType
1719 if (Status
== RETURN_OUT_OF_RESOURCES
) {
1722 Base
+= mMtrrLibFixedMtrrTable
[MsrIndex
].Length
;
1725 ASSERT (Base
== BASE_1MB
);
1726 return RETURN_SUCCESS
;
1730 Apply the variable MTRR settings to memory range array.
1732 @param VariableMtrr The variable MTRR array.
1733 @param VariableMtrrCount The count of variable MTRRs.
1734 @param Ranges Return the memory range array with new MTRR settings applied.
1735 @param RangeCapacity The capacity of memory range array.
1736 @param RangeCount Return the count of memory range.
1738 @retval RETURN_SUCCESS The memory range array is returned successfully.
1739 @retval RETURN_OUT_OF_RESOURCES The count of memory ranges exceeds capacity.
1742 MtrrLibApplyVariableMtrrs (
1743 IN CONST MTRR_MEMORY_RANGE
*VariableMtrr
,
1744 IN UINT32 VariableMtrrCount
,
1745 IN OUT MTRR_MEMORY_RANGE
*Ranges
,
1746 IN UINTN RangeCapacity
,
1747 IN OUT UINTN
*RangeCount
1750 RETURN_STATUS Status
;
1756 // UC > * (except WB, UC) > WB
1762 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
1763 if ((VariableMtrr
[Index
].Length
!= 0) && (VariableMtrr
[Index
].Type
== CacheWriteBack
)) {
1764 Status
= MtrrLibSetMemoryType (
1765 Ranges
, RangeCapacity
, RangeCount
,
1766 VariableMtrr
[Index
].BaseAddress
, VariableMtrr
[Index
].Length
, VariableMtrr
[Index
].Type
1768 if (Status
== RETURN_OUT_OF_RESOURCES
) {
1775 // 2. Set other types than WB or UC
1777 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
1778 if ((VariableMtrr
[Index
].Length
!= 0) &&
1779 (VariableMtrr
[Index
].Type
!= CacheWriteBack
) && (VariableMtrr
[Index
].Type
!= CacheUncacheable
)) {
1780 Status
= MtrrLibSetMemoryType (
1781 Ranges
, RangeCapacity
, RangeCount
,
1782 VariableMtrr
[Index
].BaseAddress
, VariableMtrr
[Index
].Length
, VariableMtrr
[Index
].Type
1784 if (Status
== RETURN_OUT_OF_RESOURCES
) {
1793 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
1794 if (VariableMtrr
[Index
].Length
!= 0 && VariableMtrr
[Index
].Type
== CacheUncacheable
) {
1795 Status
= MtrrLibSetMemoryType (
1796 Ranges
, RangeCapacity
, RangeCount
,
1797 VariableMtrr
[Index
].BaseAddress
, VariableMtrr
[Index
].Length
, VariableMtrr
[Index
].Type
1799 if (Status
== RETURN_OUT_OF_RESOURCES
) {
1804 return RETURN_SUCCESS
;
1808 Return the memory type bit mask that's compatible to first type in the Ranges.
1810 @param Ranges Memory range array holding the memory type
1811 settings for all memory address.
1812 @param RangeCount Count of memory ranges.
1814 @return Compatible memory type bit mask.
1817 MtrrLibGetCompatibleTypes (
1818 IN CONST MTRR_MEMORY_RANGE
*Ranges
,
1822 ASSERT (RangeCount
!= 0);
1824 switch (Ranges
[0].Type
) {
1825 case CacheWriteBack
:
1826 case CacheWriteThrough
:
1827 return (1 << CacheWriteBack
) | (1 << CacheWriteThrough
) | (1 << CacheUncacheable
);
1830 case CacheWriteCombining
:
1831 case CacheWriteProtected
:
1832 return (1 << Ranges
[0].Type
) | (1 << CacheUncacheable
);
1835 case CacheUncacheable
:
1836 if (RangeCount
== 1) {
1837 return (1 << CacheUncacheable
);
1839 return MtrrLibGetCompatibleTypes (&Ranges
[1], RangeCount
- 1);
1851 Overwrite the destination MTRR settings with the source MTRR settings.
1852 This routine is to make sure the modification to destination MTRR settings
1853 is as small as possible.
1855 @param DstMtrrs Destination MTRR settings.
1856 @param DstMtrrCount Count of destination MTRR settings.
1857 @param SrcMtrrs Source MTRR settings.
1858 @param SrcMtrrCount Count of source MTRR settings.
1859 @param Modified Flag array to indicate which destination MTRR setting is modified.
1862 MtrrLibMergeVariableMtrr (
1863 MTRR_MEMORY_RANGE
*DstMtrrs
,
1864 UINT32 DstMtrrCount
,
1865 MTRR_MEMORY_RANGE
*SrcMtrrs
,
1866 UINT32 SrcMtrrCount
,
1873 ASSERT (SrcMtrrCount
<= DstMtrrCount
);
1875 for (DstIndex
= 0; DstIndex
< DstMtrrCount
; DstIndex
++) {
1876 Modified
[DstIndex
] = FALSE
;
1878 if (DstMtrrs
[DstIndex
].Length
== 0) {
1881 for (SrcIndex
= 0; SrcIndex
< SrcMtrrCount
; SrcIndex
++) {
1882 if (DstMtrrs
[DstIndex
].BaseAddress
== SrcMtrrs
[SrcIndex
].BaseAddress
&&
1883 DstMtrrs
[DstIndex
].Length
== SrcMtrrs
[SrcIndex
].Length
&&
1884 DstMtrrs
[DstIndex
].Type
== SrcMtrrs
[SrcIndex
].Type
) {
1889 if (SrcIndex
== SrcMtrrCount
) {
1891 // Remove the one from DstMtrrs which is not in SrcMtrrs
1893 DstMtrrs
[DstIndex
].Length
= 0;
1894 Modified
[DstIndex
] = TRUE
;
1897 // Remove the one from SrcMtrrs which is also in DstMtrrs
1899 SrcMtrrs
[SrcIndex
].Length
= 0;
1904 // Now valid MTRR only exists in either DstMtrrs or SrcMtrrs.
1905 // Merge MTRRs from SrcMtrrs to DstMtrrs
1908 for (SrcIndex
= 0; SrcIndex
< SrcMtrrCount
; SrcIndex
++) {
1909 if (SrcMtrrs
[SrcIndex
].Length
!= 0) {
1912 // Find the empty slot in DstMtrrs
1914 while (DstIndex
< DstMtrrCount
) {
1915 if (DstMtrrs
[DstIndex
].Length
== 0) {
1920 ASSERT (DstIndex
< DstMtrrCount
);
1921 CopyMem (&DstMtrrs
[DstIndex
], &SrcMtrrs
[SrcIndex
], sizeof (SrcMtrrs
[0]));
1922 Modified
[DstIndex
] = TRUE
;
1928 Calculate the variable MTRR settings for all memory ranges.
1930 @param DefaultType Default memory type.
1931 @param A0 Alignment to use when base address is 0.
1932 @param Ranges Memory range array holding the memory type
1933 settings for all memory address.
1934 @param RangeCount Count of memory ranges.
1935 @param Scratch Scratch buffer to be used in MTRR calculation.
1936 @param ScratchSize Pointer to the size of scratch buffer.
1937 @param VariableMtrr Array holding all MTRR settings.
1938 @param VariableMtrrCapacity Capacity of the MTRR array.
1939 @param VariableMtrrCount The count of MTRR settings in array.
1941 @retval RETURN_SUCCESS Variable MTRRs are allocated successfully.
1942 @retval RETURN_OUT_OF_RESOURCES Count of variable MTRRs exceeds capacity.
1943 @retval RETURN_BUFFER_TOO_SMALL The scratch buffer is too small for MTRR calculation.
1944 The required scratch buffer size is returned through ScratchSize.
1947 MtrrLibSetMemoryRanges (
1948 IN MTRR_MEMORY_CACHE_TYPE DefaultType
,
1950 IN MTRR_MEMORY_RANGE
*Ranges
,
1951 IN UINTN RangeCount
,
1953 IN OUT UINTN
*ScratchSize
,
1954 OUT MTRR_MEMORY_RANGE
*VariableMtrr
,
1955 IN UINT32 VariableMtrrCapacity
,
1956 OUT UINT32
*VariableMtrrCount
1959 RETURN_STATUS Status
;
1964 UINT8 CompatibleTypes
;
1967 UINTN ActualScratchSize
;
1968 UINTN BiggestScratchSize
;
1970 *VariableMtrrCount
= 0;
1973 // Since the whole ranges need multiple calls of MtrrLibCalculateMtrrs().
1974 // Each call needs different scratch buffer size.
1975 // When the provided scratch buffer size is not sufficient in any call,
1976 // set the GetActualScratchSize to TRUE, and following calls will only
1977 // calculate the actual scratch size for the caller.
1979 BiggestScratchSize
= 0;
1981 for (Index
= 0; Index
< RangeCount
;) {
1982 Base0
= Ranges
[Index
].BaseAddress
;
1985 // Full step is optimal
1987 while (Index
< RangeCount
) {
1988 ASSERT (Ranges
[Index
].BaseAddress
== Base0
);
1989 Alignment
= MtrrLibBiggestAlignment (Base0
, A0
);
1990 while (Base0
+ Alignment
<= Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
) {
1991 if ((BiggestScratchSize
<= *ScratchSize
) && (Ranges
[Index
].Type
!= DefaultType
)) {
1992 Status
= MtrrLibAppendVariableMtrr (
1993 VariableMtrr
, VariableMtrrCapacity
, VariableMtrrCount
,
1994 Base0
, Alignment
, Ranges
[Index
].Type
1996 if (RETURN_ERROR (Status
)) {
2001 Alignment
= MtrrLibBiggestAlignment (Base0
, A0
);
2005 // Remove the above range from Ranges[Index]
2007 Ranges
[Index
].Length
-= Base0
- Ranges
[Index
].BaseAddress
;
2008 Ranges
[Index
].BaseAddress
= Base0
;
2009 if (Ranges
[Index
].Length
!= 0) {
2016 if (Index
== RangeCount
) {
2021 // Find continous ranges [Base0, Base1) which could be combined by MTRR.
2022 // Per SDM, the compatible types between[B0, B1) are:
2027 CompatibleTypes
= MtrrLibGetCompatibleTypes (&Ranges
[Index
], RangeCount
- Index
);
2029 End
= Index
; // End points to last one that matches the CompatibleTypes.
2030 while (End
+ 1 < RangeCount
) {
2031 if (((1 << Ranges
[End
+ 1].Type
) & CompatibleTypes
) == 0) {
2036 Alignment
= MtrrLibBiggestAlignment (Base0
, A0
);
2037 Length
= GetPowerOfTwo64 (Ranges
[End
].BaseAddress
+ Ranges
[End
].Length
- Base0
);
2038 Base1
= Base0
+ MIN (Alignment
, Length
);
2041 // Base1 may not in Ranges[End]. Update End to the range Base1 belongs to.
2044 while (End
+ 1 < RangeCount
) {
2045 if (Base1
<= Ranges
[End
+ 1].BaseAddress
) {
2051 Length
= Ranges
[End
].Length
;
2052 Ranges
[End
].Length
= Base1
- Ranges
[End
].BaseAddress
;
2053 ActualScratchSize
= *ScratchSize
;
2054 Status
= MtrrLibCalculateMtrrs (
2056 &Ranges
[Index
], End
+ 1 - Index
,
2057 Scratch
, &ActualScratchSize
,
2058 VariableMtrr
, VariableMtrrCapacity
, VariableMtrrCount
2060 if (Status
== RETURN_BUFFER_TOO_SMALL
) {
2061 BiggestScratchSize
= MAX (BiggestScratchSize
, ActualScratchSize
);
2063 // Ignore this error, because we need to calculate the biggest
2064 // scratch buffer size.
2066 Status
= RETURN_SUCCESS
;
2068 if (RETURN_ERROR (Status
)) {
2072 if (Length
!= Ranges
[End
].Length
) {
2073 Ranges
[End
].BaseAddress
= Base1
;
2074 Ranges
[End
].Length
= Length
- Ranges
[End
].Length
;
2081 if (*ScratchSize
< BiggestScratchSize
) {
2082 *ScratchSize
= BiggestScratchSize
;
2083 return RETURN_BUFFER_TOO_SMALL
;
2085 return RETURN_SUCCESS
;
2089 Set the below-1MB memory attribute to fixed MTRR buffer.
2090 Modified flag array indicates which fixed MTRR is modified.
2092 @param [in, out] FixedSettings Fixed MTRR buffer.
2093 @param [out] Modified Flag array indicating which MTRR is modified.
2094 @param [in] BaseAddress Base address.
2095 @param [in] Length Length.
2096 @param [in] Type Memory type.
2098 @retval RETURN_SUCCESS The memory attribute is set successfully.
2099 @retval RETURN_UNSUPPORTED The requested range or cache type was invalid
2100 for the fixed MTRRs.
2103 MtrrLibSetBelow1MBMemoryAttribute (
2104 IN OUT MTRR_FIXED_SETTINGS
*FixedSettings
,
2105 OUT BOOLEAN
*Modified
,
2106 IN PHYSICAL_ADDRESS BaseAddress
,
2108 IN MTRR_MEMORY_CACHE_TYPE Type
2111 RETURN_STATUS Status
;
2115 UINT64 ClearMasks
[ARRAY_SIZE (mMtrrLibFixedMtrrTable
)];
2116 UINT64 OrMasks
[ARRAY_SIZE (mMtrrLibFixedMtrrTable
)];
2117 BOOLEAN LocalModified
[ARRAY_SIZE (mMtrrLibFixedMtrrTable
)];
2119 ASSERT (BaseAddress
< BASE_1MB
);
2121 SetMem (LocalModified
, sizeof (LocalModified
), FALSE
);
2124 // (Value & ~0 | 0) still equals to (Value)
2126 SetMem (ClearMasks
, sizeof (ClearMasks
), 0);
2127 SetMem (OrMasks
, sizeof (OrMasks
), 0);
2129 MsrIndex
= (UINT32
)-1;
2130 while ((BaseAddress
< BASE_1MB
) && (Length
!= 0)) {
2131 Status
= MtrrLibProgramFixedMtrr (Type
, &BaseAddress
, &Length
, &MsrIndex
, &ClearMask
, &OrMask
);
2132 if (RETURN_ERROR (Status
)) {
2135 ClearMasks
[MsrIndex
] = ClearMask
;
2136 OrMasks
[MsrIndex
] = OrMask
;
2137 Modified
[MsrIndex
] = TRUE
;
2138 LocalModified
[MsrIndex
] = TRUE
;
2141 for (MsrIndex
= 0; MsrIndex
< ARRAY_SIZE (mMtrrLibFixedMtrrTable
); MsrIndex
++) {
2142 if (LocalModified
[MsrIndex
]) {
2143 FixedSettings
->Mtrr
[MsrIndex
] = (FixedSettings
->Mtrr
[MsrIndex
] & ~ClearMasks
[MsrIndex
]) | OrMasks
[MsrIndex
];
2146 return RETURN_SUCCESS
;
2150 This function attempts to set the attributes into MTRR setting buffer for multiple memory ranges.
2152 @param[in, out] MtrrSetting MTRR setting buffer to be set.
2153 @param[in] Scratch A temporary scratch buffer that is used to perform the calculation.
2154 @param[in, out] ScratchSize Pointer to the size in bytes of the scratch buffer.
2155 It may be updated to the actual required size when the calculation
2156 needs more scratch buffer.
2157 @param[in] Ranges Pointer to an array of MTRR_MEMORY_RANGE.
2158 When range overlap happens, the last one takes higher priority.
2159 When the function returns, either all the attributes are set successfully,
2160 or none of them is set.
2161 @param[in] RangeCount Count of MTRR_MEMORY_RANGE.
2163 @retval RETURN_SUCCESS The attributes were set for all the memory ranges.
2164 @retval RETURN_INVALID_PARAMETER Length in any range is zero.
2165 @retval RETURN_UNSUPPORTED The processor does not support one or more bytes of the
2166 memory resource range specified by BaseAddress and Length in any range.
2167 @retval RETURN_UNSUPPORTED The bit mask of attributes is not support for the memory resource
2168 range specified by BaseAddress and Length in any range.
2169 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of
2170 the memory resource ranges.
2171 @retval RETURN_ACCESS_DENIED The attributes for the memory resource range specified by
2172 BaseAddress and Length cannot be modified.
2173 @retval RETURN_BUFFER_TOO_SMALL The scratch buffer is too small for MTRR calculation.
2177 MtrrSetMemoryAttributesInMtrrSettings (
2178 IN OUT MTRR_SETTINGS
*MtrrSetting
,
2180 IN OUT UINTN
*ScratchSize
,
2181 IN CONST MTRR_MEMORY_RANGE
*Ranges
,
2185 RETURN_STATUS Status
;
2189 BOOLEAN Above1MbExist
;
2191 UINT64 MtrrValidBitsMask
;
2192 UINT64 MtrrValidAddressMask
;
2193 MTRR_MEMORY_CACHE_TYPE DefaultType
;
2194 MTRR_VARIABLE_SETTINGS VariableSettings
;
2195 MTRR_MEMORY_RANGE WorkingRanges
[2 * ARRAY_SIZE (MtrrSetting
->Variables
.Mtrr
) + 2];
2196 UINTN WorkingRangeCount
;
2198 MTRR_VARIABLE_SETTING VariableSetting
;
2199 UINT32 OriginalVariableMtrrCount
;
2200 UINT32 FirmwareVariableMtrrCount
;
2201 UINT32 WorkingVariableMtrrCount
;
2202 MTRR_MEMORY_RANGE OriginalVariableMtrr
[ARRAY_SIZE (MtrrSetting
->Variables
.Mtrr
)];
2203 MTRR_MEMORY_RANGE WorkingVariableMtrr
[ARRAY_SIZE (MtrrSetting
->Variables
.Mtrr
)];
2204 BOOLEAN VariableSettingModified
[ARRAY_SIZE (MtrrSetting
->Variables
.Mtrr
)];
2206 BOOLEAN FixedSettingsModified
[ARRAY_SIZE (mMtrrLibFixedMtrrTable
)];
2207 MTRR_FIXED_SETTINGS WorkingFixedSettings
;
2209 MTRR_CONTEXT MtrrContext
;
2210 BOOLEAN MtrrContextValid
;
2212 MtrrLibInitializeMtrrMask (&MtrrValidBitsMask
, &MtrrValidAddressMask
);
2215 // TRUE indicating the accordingly Variable setting needs modificaiton in OriginalVariableMtrr.
2217 SetMem (VariableSettingModified
, ARRAY_SIZE (VariableSettingModified
), FALSE
);
2219 // TRUE indicating the accordingly Fixed setting needs modification in WorkingFixedSettings.
2221 SetMem (FixedSettingsModified
, ARRAY_SIZE (FixedSettingsModified
), FALSE
);
2224 // TRUE indicating the caller requests to set variable MTRRs.
2226 Above1MbExist
= FALSE
;
2227 OriginalVariableMtrrCount
= 0;
2230 // 1. Validate the parameters.
2232 for (Index
= 0; Index
< RangeCount
; Index
++) {
2233 if (Ranges
[Index
].Length
== 0) {
2234 return RETURN_INVALID_PARAMETER
;
2236 if (((Ranges
[Index
].BaseAddress
& ~MtrrValidAddressMask
) != 0) ||
2237 ((Ranges
[Index
].Length
& ~MtrrValidAddressMask
) != 0)
2239 return RETURN_UNSUPPORTED
;
2241 if ((Ranges
[Index
].Type
!= CacheUncacheable
) &&
2242 (Ranges
[Index
].Type
!= CacheWriteCombining
) &&
2243 (Ranges
[Index
].Type
!= CacheWriteThrough
) &&
2244 (Ranges
[Index
].Type
!= CacheWriteProtected
) &&
2245 (Ranges
[Index
].Type
!= CacheWriteBack
)) {
2246 return RETURN_INVALID_PARAMETER
;
2248 if (Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
> BASE_1MB
) {
2249 Above1MbExist
= TRUE
;
2254 // 2. Apply the above-1MB memory attribute settings.
2256 if (Above1MbExist
) {
2258 // 2.1. Read all variable MTRRs and convert to Ranges.
2260 OriginalVariableMtrrCount
= GetVariableMtrrCountWorker ();
2261 MtrrGetVariableMtrrWorker (MtrrSetting
, OriginalVariableMtrrCount
, &VariableSettings
);
2262 MtrrLibGetRawVariableRanges (
2263 &VariableSettings
, OriginalVariableMtrrCount
,
2264 MtrrValidBitsMask
, MtrrValidAddressMask
, OriginalVariableMtrr
2267 DefaultType
= MtrrGetDefaultMemoryTypeWorker (MtrrSetting
);
2268 WorkingRangeCount
= 1;
2269 WorkingRanges
[0].BaseAddress
= 0;
2270 WorkingRanges
[0].Length
= MtrrValidBitsMask
+ 1;
2271 WorkingRanges
[0].Type
= DefaultType
;
2273 Status
= MtrrLibApplyVariableMtrrs (
2274 OriginalVariableMtrr
, OriginalVariableMtrrCount
,
2275 WorkingRanges
, ARRAY_SIZE (WorkingRanges
), &WorkingRangeCount
);
2276 ASSERT_RETURN_ERROR (Status
);
2278 ASSERT (OriginalVariableMtrrCount
>= PcdGet32 (PcdCpuNumberOfReservedVariableMtrrs
));
2279 FirmwareVariableMtrrCount
= OriginalVariableMtrrCount
- PcdGet32 (PcdCpuNumberOfReservedVariableMtrrs
);
2280 ASSERT (WorkingRangeCount
<= 2 * FirmwareVariableMtrrCount
+ 1);
2283 // 2.2. Force [0, 1M) to UC, so that it doesn't impact subtraction algorithm.
2285 Status
= MtrrLibSetMemoryType (
2286 WorkingRanges
, ARRAY_SIZE (WorkingRanges
), &WorkingRangeCount
,
2287 0, SIZE_1MB
, CacheUncacheable
2289 ASSERT (Status
!= RETURN_OUT_OF_RESOURCES
);
2292 // 2.3. Apply the new memory attribute settings to Ranges.
2295 for (Index
= 0; Index
< RangeCount
; Index
++) {
2296 BaseAddress
= Ranges
[Index
].BaseAddress
;
2297 Length
= Ranges
[Index
].Length
;
2298 if (BaseAddress
< BASE_1MB
) {
2299 if (Length
<= BASE_1MB
- BaseAddress
) {
2302 Length
-= BASE_1MB
- BaseAddress
;
2303 BaseAddress
= BASE_1MB
;
2305 Status
= MtrrLibSetMemoryType (
2306 WorkingRanges
, ARRAY_SIZE (WorkingRanges
), &WorkingRangeCount
,
2307 BaseAddress
, Length
, Ranges
[Index
].Type
2309 if (Status
== RETURN_ALREADY_STARTED
) {
2310 Status
= RETURN_SUCCESS
;
2311 } else if (Status
== RETURN_OUT_OF_RESOURCES
) {
2314 ASSERT_RETURN_ERROR (Status
);
2321 // 2.4. Calculate the Variable MTRR settings based on the Ranges.
2322 // Buffer Too Small may be returned if the scratch buffer size is insufficient.
2324 Status
= MtrrLibSetMemoryRanges (
2325 DefaultType
, LShiftU64 (1, (UINTN
)HighBitSet64 (MtrrValidBitsMask
)), WorkingRanges
, WorkingRangeCount
,
2326 Scratch
, ScratchSize
,
2327 WorkingVariableMtrr
, FirmwareVariableMtrrCount
+ 1, &WorkingVariableMtrrCount
2329 if (RETURN_ERROR (Status
)) {
2334 // 2.5. Remove the [0, 1MB) MTRR if it still exists (not merged with other range)
2336 for (Index
= 0; Index
< WorkingVariableMtrrCount
; Index
++) {
2337 if (WorkingVariableMtrr
[Index
].BaseAddress
== 0 && WorkingVariableMtrr
[Index
].Length
== SIZE_1MB
) {
2338 ASSERT (WorkingVariableMtrr
[Index
].Type
== CacheUncacheable
);
2339 WorkingVariableMtrrCount
--;
2341 &WorkingVariableMtrr
[Index
], &WorkingVariableMtrr
[Index
+ 1],
2342 (WorkingVariableMtrrCount
- Index
) * sizeof (WorkingVariableMtrr
[0])
2348 if (WorkingVariableMtrrCount
> FirmwareVariableMtrrCount
) {
2349 return RETURN_OUT_OF_RESOURCES
;
2353 // 2.6. Merge the WorkingVariableMtrr to OriginalVariableMtrr
2354 // Make sure least modification is made to OriginalVariableMtrr.
2356 MtrrLibMergeVariableMtrr (
2357 OriginalVariableMtrr
, OriginalVariableMtrrCount
,
2358 WorkingVariableMtrr
, WorkingVariableMtrrCount
,
2359 VariableSettingModified
2365 // 3. Apply the below-1MB memory attribute settings.
2367 ZeroMem (WorkingFixedSettings
.Mtrr
, sizeof (WorkingFixedSettings
.Mtrr
));
2368 for (Index
= 0; Index
< RangeCount
; Index
++) {
2369 if (Ranges
[Index
].BaseAddress
>= BASE_1MB
) {
2373 Status
= MtrrLibSetBelow1MBMemoryAttribute (
2374 &WorkingFixedSettings
, FixedSettingsModified
,
2375 Ranges
[Index
].BaseAddress
, Ranges
[Index
].Length
, Ranges
[Index
].Type
2377 if (RETURN_ERROR (Status
)) {
2382 MtrrContextValid
= FALSE
;
2384 // 4. Write fixed MTRRs that have been modified
2386 for (Index
= 0; Index
< ARRAY_SIZE (FixedSettingsModified
); Index
++) {
2387 if (FixedSettingsModified
[Index
]) {
2388 if (MtrrSetting
!= NULL
) {
2389 MtrrSetting
->Fixed
.Mtrr
[Index
] = WorkingFixedSettings
.Mtrr
[Index
];
2391 if (!MtrrContextValid
) {
2392 MtrrLibPreMtrrChange (&MtrrContext
);
2393 MtrrContextValid
= TRUE
;
2396 mMtrrLibFixedMtrrTable
[Index
].Msr
,
2397 WorkingFixedSettings
.Mtrr
[Index
]
2404 // 5. Write variable MTRRs that have been modified
2406 for (Index
= 0; Index
< OriginalVariableMtrrCount
; Index
++) {
2407 if (VariableSettingModified
[Index
]) {
2408 if (OriginalVariableMtrr
[Index
].Length
!= 0) {
2409 VariableSetting
.Base
= (OriginalVariableMtrr
[Index
].BaseAddress
& MtrrValidAddressMask
)
2410 | (UINT8
)OriginalVariableMtrr
[Index
].Type
;
2411 VariableSetting
.Mask
= ((~(OriginalVariableMtrr
[Index
].Length
- 1)) & MtrrValidAddressMask
) | BIT11
;
2413 VariableSetting
.Base
= 0;
2414 VariableSetting
.Mask
= 0;
2416 if (MtrrSetting
!= NULL
) {
2417 CopyMem (&MtrrSetting
->Variables
.Mtrr
[Index
], &VariableSetting
, sizeof (VariableSetting
));
2419 if (!MtrrContextValid
) {
2420 MtrrLibPreMtrrChange (&MtrrContext
);
2421 MtrrContextValid
= TRUE
;
2424 MSR_IA32_MTRR_PHYSBASE0
+ (Index
<< 1),
2425 VariableSetting
.Base
2428 MSR_IA32_MTRR_PHYSMASK0
+ (Index
<< 1),
2429 VariableSetting
.Mask
2435 if (MtrrSetting
!= NULL
) {
2436 ((MSR_IA32_MTRR_DEF_TYPE_REGISTER
*)&MtrrSetting
->MtrrDefType
)->Bits
.E
= 1;
2437 ((MSR_IA32_MTRR_DEF_TYPE_REGISTER
*)&MtrrSetting
->MtrrDefType
)->Bits
.FE
= 1;
2439 if (MtrrContextValid
) {
2440 MtrrLibPostMtrrChange (&MtrrContext
);
2444 return RETURN_SUCCESS
;
2448 This function attempts to set the attributes into MTRR setting buffer for a memory range.
2450 @param[in, out] MtrrSetting MTRR setting buffer to be set.
2451 @param[in] BaseAddress The physical address that is the start address
2453 @param[in] Length The size in bytes of the memory range.
2454 @param[in] Attribute The bit mask of attributes to set for the
2457 @retval RETURN_SUCCESS The attributes were set for the memory range.
2458 @retval RETURN_INVALID_PARAMETER Length is zero.
2459 @retval RETURN_UNSUPPORTED The processor does not support one or more bytes of the
2460 memory resource range specified by BaseAddress and Length.
2461 @retval RETURN_UNSUPPORTED The bit mask of attributes is not support for the memory resource
2462 range specified by BaseAddress and Length.
2463 @retval RETURN_ACCESS_DENIED The attributes for the memory resource range specified by
2464 BaseAddress and Length cannot be modified.
2465 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of
2466 the memory resource range.
2467 @retval RETURN_BUFFER_TOO_SMALL The scratch buffer is too small for MTRR calculation.
2471 MtrrSetMemoryAttributeInMtrrSettings (
2472 IN OUT MTRR_SETTINGS
*MtrrSetting
,
2473 IN PHYSICAL_ADDRESS BaseAddress
,
2475 IN MTRR_MEMORY_CACHE_TYPE Attribute
2478 RETURN_STATUS Status
;
2479 UINT8 Scratch
[SCRATCH_BUFFER_SIZE
];
2481 MTRR_MEMORY_RANGE Range
;
2483 if (!IsMtrrSupported ()) {
2484 return RETURN_UNSUPPORTED
;
2487 Range
.BaseAddress
= BaseAddress
;
2488 Range
.Length
= Length
;
2489 Range
.Type
= Attribute
;
2490 ScratchSize
= sizeof (Scratch
);
2491 Status
= MtrrSetMemoryAttributesInMtrrSettings (MtrrSetting
, Scratch
, &ScratchSize
, &Range
, 1);
2492 DEBUG ((DEBUG_CACHE
, "MtrrSetMemoryAttribute(MtrrSettings = %p) %a: [%016lx, %016lx) - %r\n",
2494 mMtrrMemoryCacheTypeShortName
[Attribute
], BaseAddress
, BaseAddress
+ Length
, Status
));
2496 if (!RETURN_ERROR (Status
)) {
2497 MtrrDebugPrintAllMtrrsWorker (MtrrSetting
);
2503 This function attempts to set the attributes for a memory range.
2505 @param[in] BaseAddress The physical address that is the start
2506 address of a memory range.
2507 @param[in] Length The size in bytes of the memory range.
2508 @param[in] Attributes The bit mask of attributes to set for the
2511 @retval RETURN_SUCCESS The attributes were set for the memory
2513 @retval RETURN_INVALID_PARAMETER Length is zero.
2514 @retval RETURN_UNSUPPORTED The processor does not support one or
2515 more bytes of the memory resource range
2516 specified by BaseAddress and Length.
2517 @retval RETURN_UNSUPPORTED The bit mask of attributes is not support
2518 for the memory resource range specified
2519 by BaseAddress and Length.
2520 @retval RETURN_ACCESS_DENIED The attributes for the memory resource
2521 range specified by BaseAddress and Length
2523 @retval RETURN_OUT_OF_RESOURCES There are not enough system resources to
2524 modify the attributes of the memory
2526 @retval RETURN_BUFFER_TOO_SMALL The scratch buffer is too small for MTRR calculation.
2530 MtrrSetMemoryAttribute (
2531 IN PHYSICAL_ADDRESS BaseAddress
,
2533 IN MTRR_MEMORY_CACHE_TYPE Attribute
2536 return MtrrSetMemoryAttributeInMtrrSettings (NULL
, BaseAddress
, Length
, Attribute
);
2540 Worker function setting variable MTRRs
2542 @param[in] VariableSettings A buffer to hold variable MTRRs content.
2546 MtrrSetVariableMtrrWorker (
2547 IN MTRR_VARIABLE_SETTINGS
*VariableSettings
2551 UINT32 VariableMtrrCount
;
2553 VariableMtrrCount
= GetVariableMtrrCountWorker ();
2554 ASSERT (VariableMtrrCount
<= ARRAY_SIZE (VariableSettings
->Mtrr
));
2556 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
2558 // Mask MSR is always updated since caller might need to invalidate the MSR pair.
2559 // Base MSR is skipped when Mask.V is not set.
2561 AsmWriteMsr64 (MSR_IA32_MTRR_PHYSMASK0
+ (Index
<< 1), VariableSettings
->Mtrr
[Index
].Mask
);
2562 if (((MSR_IA32_MTRR_PHYSMASK_REGISTER
*)&VariableSettings
->Mtrr
[Index
].Mask
)->Bits
.V
!= 0) {
2563 AsmWriteMsr64 (MSR_IA32_MTRR_PHYSBASE0
+ (Index
<< 1), VariableSettings
->Mtrr
[Index
].Base
);
2570 This function sets variable MTRRs
2572 @param[in] VariableSettings A buffer to hold variable MTRRs content.
2574 @return The pointer of VariableSettings
2577 MTRR_VARIABLE_SETTINGS
*
2579 MtrrSetVariableMtrr (
2580 IN MTRR_VARIABLE_SETTINGS
*VariableSettings
2583 MTRR_CONTEXT MtrrContext
;
2585 if (!IsMtrrSupported ()) {
2586 return VariableSettings
;
2589 MtrrLibPreMtrrChange (&MtrrContext
);
2590 MtrrSetVariableMtrrWorker (VariableSettings
);
2591 MtrrLibPostMtrrChange (&MtrrContext
);
2592 MtrrDebugPrintAllMtrrs ();
2594 return VariableSettings
;
2598 Worker function setting fixed MTRRs
2600 @param[in] FixedSettings A buffer to hold fixed MTRRs content.
2604 MtrrSetFixedMtrrWorker (
2605 IN MTRR_FIXED_SETTINGS
*FixedSettings
2610 for (Index
= 0; Index
< MTRR_NUMBER_OF_FIXED_MTRR
; Index
++) {
2612 mMtrrLibFixedMtrrTable
[Index
].Msr
,
2613 FixedSettings
->Mtrr
[Index
]
2620 This function sets fixed MTRRs
2622 @param[in] FixedSettings A buffer to hold fixed MTRRs content.
2624 @retval The pointer of FixedSettings
2627 MTRR_FIXED_SETTINGS
*
2630 IN MTRR_FIXED_SETTINGS
*FixedSettings
2633 MTRR_CONTEXT MtrrContext
;
2635 if (!IsMtrrSupported ()) {
2636 return FixedSettings
;
2639 MtrrLibPreMtrrChange (&MtrrContext
);
2640 MtrrSetFixedMtrrWorker (FixedSettings
);
2641 MtrrLibPostMtrrChange (&MtrrContext
);
2642 MtrrDebugPrintAllMtrrs ();
2644 return FixedSettings
;
2649 This function gets the content in all MTRRs (variable and fixed)
2651 @param[out] MtrrSetting A buffer to hold all MTRRs content.
2653 @retval the pointer of MtrrSetting
2659 OUT MTRR_SETTINGS
*MtrrSetting
2662 if (!IsMtrrSupported ()) {
2669 MtrrGetFixedMtrrWorker (&MtrrSetting
->Fixed
);
2672 // Get variable MTRRs
2674 MtrrGetVariableMtrrWorker (
2676 GetVariableMtrrCountWorker (),
2677 &MtrrSetting
->Variables
2681 // Get MTRR_DEF_TYPE value
2683 MtrrSetting
->MtrrDefType
= AsmReadMsr64 (MSR_IA32_MTRR_DEF_TYPE
);
2690 This function sets all MTRRs (variable and fixed)
2692 @param[in] MtrrSetting A buffer holding all MTRRs content.
2694 @retval The pointer of MtrrSetting
2700 IN MTRR_SETTINGS
*MtrrSetting
2703 MTRR_CONTEXT MtrrContext
;
2705 if (!IsMtrrSupported ()) {
2709 MtrrLibPreMtrrChange (&MtrrContext
);
2714 MtrrSetFixedMtrrWorker (&MtrrSetting
->Fixed
);
2717 // Set variable MTRRs
2719 MtrrSetVariableMtrrWorker (&MtrrSetting
->Variables
);
2722 // Set MTRR_DEF_TYPE value
2724 AsmWriteMsr64 (MSR_IA32_MTRR_DEF_TYPE
, MtrrSetting
->MtrrDefType
);
2726 MtrrLibPostMtrrChangeEnableCache (&MtrrContext
);
2733 Checks if MTRR is supported.
2735 @retval TRUE MTRR is supported.
2736 @retval FALSE MTRR is not supported.
2745 CPUID_VERSION_INFO_EDX Edx
;
2746 MSR_IA32_MTRRCAP_REGISTER MtrrCap
;
2749 // Check CPUID(1).EDX[12] for MTRR capability
2751 AsmCpuid (CPUID_VERSION_INFO
, NULL
, NULL
, NULL
, &Edx
.Uint32
);
2752 if (Edx
.Bits
.MTRR
== 0) {
2757 // Check number of variable MTRRs and fixed MTRRs existence.
2758 // If number of variable MTRRs is zero, or fixed MTRRs do not
2759 // exist, return false.
2761 MtrrCap
.Uint64
= AsmReadMsr64 (MSR_IA32_MTRRCAP
);
2762 if ((MtrrCap
.Bits
.VCNT
== 0) || (MtrrCap
.Bits
.FIX
== 0)) {
2770 Worker function prints all MTRRs for debugging.
2772 If MtrrSetting is not NULL, print MTRR settings from input MTRR
2774 If MtrrSetting is NULL, print MTRR settings from MTRRs.
2776 @param MtrrSetting A buffer holding all MTRRs content.
2779 MtrrDebugPrintAllMtrrsWorker (
2780 IN MTRR_SETTINGS
*MtrrSetting
2784 MTRR_SETTINGS LocalMtrrs
;
2785 MTRR_SETTINGS
*Mtrrs
;
2788 UINT64 MtrrValidBitsMask
;
2789 UINT64 MtrrValidAddressMask
;
2790 UINT32 VariableMtrrCount
;
2791 MTRR_MEMORY_RANGE Ranges
[
2792 ARRAY_SIZE (mMtrrLibFixedMtrrTable
) * sizeof (UINT64
) + 2 * ARRAY_SIZE (Mtrrs
->Variables
.Mtrr
) + 1
2794 MTRR_MEMORY_RANGE RawVariableRanges
[ARRAY_SIZE (Mtrrs
->Variables
.Mtrr
)];
2796 if (!IsMtrrSupported ()) {
2800 VariableMtrrCount
= GetVariableMtrrCountWorker ();
2802 if (MtrrSetting
!= NULL
) {
2803 Mtrrs
= MtrrSetting
;
2805 MtrrGetAllMtrrs (&LocalMtrrs
);
2806 Mtrrs
= &LocalMtrrs
;
2810 // Dump RAW MTRR contents
2812 DEBUG((DEBUG_CACHE
, "MTRR Settings\n"));
2813 DEBUG((DEBUG_CACHE
, "=============\n"));
2814 DEBUG((DEBUG_CACHE
, "MTRR Default Type: %016lx\n", Mtrrs
->MtrrDefType
));
2815 for (Index
= 0; Index
< ARRAY_SIZE (mMtrrLibFixedMtrrTable
); Index
++) {
2816 DEBUG((DEBUG_CACHE
, "Fixed MTRR[%02d] : %016lx\n", Index
, Mtrrs
->Fixed
.Mtrr
[Index
]));
2819 for (Index
= 0; Index
< VariableMtrrCount
; Index
++) {
2820 if (((MSR_IA32_MTRR_PHYSMASK_REGISTER
*)&Mtrrs
->Variables
.Mtrr
[Index
].Mask
)->Bits
.V
== 0) {
2822 // If mask is not valid, then do not display range
2826 DEBUG ((DEBUG_CACHE
, "Variable MTRR[%02d]: Base=%016lx Mask=%016lx\n",
2828 Mtrrs
->Variables
.Mtrr
[Index
].Base
,
2829 Mtrrs
->Variables
.Mtrr
[Index
].Mask
2832 DEBUG((DEBUG_CACHE
, "\n"));
2835 // Dump MTRR setting in ranges
2837 DEBUG((DEBUG_CACHE
, "MTRR Ranges\n"));
2838 DEBUG((DEBUG_CACHE
, "====================================\n"));
2839 MtrrLibInitializeMtrrMask (&MtrrValidBitsMask
, &MtrrValidAddressMask
);
2840 Ranges
[0].BaseAddress
= 0;
2841 Ranges
[0].Length
= MtrrValidBitsMask
+ 1;
2842 Ranges
[0].Type
= MtrrGetDefaultMemoryTypeWorker (Mtrrs
);
2845 MtrrLibGetRawVariableRanges (
2846 &Mtrrs
->Variables
, VariableMtrrCount
,
2847 MtrrValidBitsMask
, MtrrValidAddressMask
, RawVariableRanges
2849 MtrrLibApplyVariableMtrrs (
2850 RawVariableRanges
, VariableMtrrCount
,
2851 Ranges
, ARRAY_SIZE (Ranges
), &RangeCount
2854 MtrrLibApplyFixedMtrrs (&Mtrrs
->Fixed
, Ranges
, ARRAY_SIZE (Ranges
), &RangeCount
);
2856 for (Index
= 0; Index
< RangeCount
; Index
++) {
2857 DEBUG ((DEBUG_CACHE
, "%a:%016lx-%016lx\n",
2858 mMtrrMemoryCacheTypeShortName
[Ranges
[Index
].Type
],
2859 Ranges
[Index
].BaseAddress
, Ranges
[Index
].BaseAddress
+ Ranges
[Index
].Length
- 1
2866 This function prints all MTRRs for debugging.
2870 MtrrDebugPrintAllMtrrs (
2874 MtrrDebugPrintAllMtrrsWorker (NULL
);