[PATCH v5 02/15] x86/mtrr: optimize mtrr_calc_physbits()

From: Juergen Gross
Date: Sat Apr 01 2023 - 02:37:16 EST


Optimize mtrr_calc_physbits() for better readability.

Drop a stale comment, as reality has made it obsolete.

[ bp:
- s/mtrr/MTRR/
- s/boot_cpu_has/cpu_feature_enabled/
- use GENMASK_ULL
- simplify. ]

Signed-off-by: Juergen Gross <jgross@xxxxxxxx>
Signed-off-by: Borislav Petkov (AMD) <bp@xxxxxxxxx>
Tested-by: Michael Kelley <mikelley@xxxxxxxxxxxxx>
---
V3:
- new patch, split off from previous patch (Boris Petkov)
V5:
- add some modifications by Boris Petkov
---
arch/x86/kernel/cpu/mtrr/mtrr.c | 27 +++++++--------------------
1 file changed, 7 insertions(+), 20 deletions(-)

diff --git a/arch/x86/kernel/cpu/mtrr/mtrr.c b/arch/x86/kernel/cpu/mtrr/mtrr.c
index 8310bdb111d0..ce0b82209ad3 100644
--- a/arch/x86/kernel/cpu/mtrr/mtrr.c
+++ b/arch/x86/kernel/cpu/mtrr/mtrr.c
@@ -619,8 +619,6 @@ static struct syscore_ops mtrr_syscore_ops = {

int __initdata changed_by_mtrr_cleanup;

-#define SIZE_OR_MASK_BITS(n) (~((1ULL << ((n) - PAGE_SHIFT)) - 1))
-
static unsigned int __init mtrr_calc_physbits(bool generic)
{
unsigned int phys_addr;
@@ -628,15 +626,8 @@ static unsigned int __init mtrr_calc_physbits(bool generic)
phys_addr = 32;

if (generic) {
- size_or_mask = SIZE_OR_MASK_BITS(36);
- size_and_mask = 0x00f00000;
phys_addr = 36;

- /*
- * This is an AMD specific MSR, but we assume(hope?) that
- * Intel will implement it too when they extend the address
- * bus of the Xeon.
- */
if (cpuid_eax(0x80000000) >= 0x80000008) {
phys_addr = cpuid_eax(0x80000008) & 0xff;
/* CPUID workaround for Intel 0F33/0F34 CPU */
@@ -647,41 +638,37 @@ static unsigned int __init mtrr_calc_physbits(bool generic)
boot_cpu_data.x86_stepping == 0x4))
phys_addr = 36;

- size_or_mask = SIZE_OR_MASK_BITS(phys_addr);
- size_and_mask = ~size_or_mask & 0xfffff00000ULL;
} else if (boot_cpu_data.x86_vendor == X86_VENDOR_CENTAUR &&
boot_cpu_data.x86 == 6) {
/*
* VIA C* family have Intel style MTRRs,
* but don't support PAE
*/
- size_or_mask = SIZE_OR_MASK_BITS(32);
- size_and_mask = 0;
phys_addr = 32;
}
- } else {
- size_or_mask = SIZE_OR_MASK_BITS(32);
- size_and_mask = 0;
}

+ size_or_mask = ~GENMASK_ULL(phys_addr - PAGE_SHIFT - 1, 0);
+ size_and_mask = ~size_or_mask & GENMASK_ULL(39, 20);
+
return phys_addr;
}

/**
- * mtrr_bp_init - initialize mtrrs on the boot CPU
+ * mtrr_bp_init - initialize MTRRs on the boot CPU
*
* This needs to be called early; before any of the other CPUs are
* initialized (i.e. before smp_init()).
- *
*/
void __init mtrr_bp_init(void)
{
+ bool generic_mtrrs = cpu_feature_enabled(X86_FEATURE_MTRR);
const char *why = "(not available)";
unsigned int phys_addr;

- phys_addr = mtrr_calc_physbits(boot_cpu_has(X86_FEATURE_MTRR));
+ phys_addr = mtrr_calc_physbits(generic_mtrrs);

- if (boot_cpu_has(X86_FEATURE_MTRR)) {
+ if (generic_mtrrs) {
mtrr_if = &generic_mtrr_ops;
} else {
switch (boot_cpu_data.x86_vendor) {
--
2.35.3