Debian Codegraph @

src/cpu/x86/mtrr/mtrrlib.c

raw symbols SCIP
1 /* SPDX-License-Identifier: GPL-2.0-only */
2
3 #include <cpu/cpu.h>
4 #include <cpu/x86/mtrr.h>
5 #include <cpu/x86/msr.h>
6 #include <console/console.h>
7 #include <commonlib/bsd/helpers.h>
8 #include <types.h>
9
10 /*
11 * Get first available variable MTRR.
12 * Returns var# if available, else returns -1.
13 */
14 int get_free_var_mtrr(void)
15 {
16 msr_t maskm;
17 int vcnt;
18 int i;
19
20 vcnt = get_var_mtrr_count();
21
22 /* Identify the first var mtrr which is not valid. */
23 for (i = 0; i < vcnt; i++) {
24 maskm = rdmsr(MTRR_PHYS_MASK(i));
25 if ((maskm.lo & MTRR_PHYS_MASK_VALID) == 0)
26 return i;
27 }
28
29 /* No free var mtrr. */
30 return -1;
31 }
32
33 /*
34 * Sets the specified variable MTRR (as per index) with the
35 * given base, size, and memory type.
36 */
37 void set_var_mtrr(
38 unsigned int index, unsigned int base, unsigned int size,
39 unsigned int type)
40 {
41 /* Bit 32-35 of MTRRphysMask should be set to 1 */
42 /* FIXME: It only support 4G less range */
43 msr_t basem, maskm;
44
45 if (type == MTRR_TYPE_WRBACK && !is_cache_sets_power_of_two() && ENV_CACHE_AS_RAM)
46 printk(BIOS_ERR, "MTRR Error: Type %x may not be supported due to NEM limitation\n",
47 type);
48 if (!IS_POWER_OF_2(size))
49 printk(BIOS_ERR, "MTRR Error: size %#x is not a power of two\n", size);
50 if (size < 4 * KiB)
51 printk(BIOS_ERR, "MTRR Error: size %#x smaller than 4KiB\n", size);
52 if (base % size != 0)
53 printk(BIOS_ERR, "MTRR Error: base %#x must be aligned to size %#x\n", base,
54 size);
55
56 basem.lo = base | type;
57 basem.hi = 0;
58 wrmsr(MTRR_PHYS_BASE(index), basem);
59 maskm.lo = ~(size - 1) | MTRR_PHYS_MASK_VALID;
60 maskm.hi = (1 << (cpu_phys_address_size() - 32)) - 1;
61 wrmsr(MTRR_PHYS_MASK(index), maskm);
62 }
63
64 /* Disables the variable MTRR at the given index by clearing its base and mask MSRs. */
65 void clear_var_mtrr(int index)
66 {
67 msr_t msr = { .lo = 0, .hi = 0 };
68
69 wrmsr(MTRR_PHYS_BASE(index), msr);
70 wrmsr(MTRR_PHYS_MASK(index), msr);
71 }
72
73 /*
74 * Acquires a free variable MTRR, configures it with the given base, size, and type.
75 * Returns the MTRR index if successful (>=0), or an error code (<0) if acquisition failed.
76 */
77 int acquire_and_configure_mtrr(unsigned int base, unsigned int size, unsigned int type)
78 {
79 int index = get_free_var_mtrr();
80
81 if (index >= 0)
82 set_var_mtrr(index, base, size, type);
83
84 return index;
85 }