1 // SPDX-License-Identifier: GPL-2.0-only
3 * AMD SVM-SEV Host Support.
5 * Copyright (C) 2023 Advanced Micro Devices, Inc.
7 * Author: Ashish Kalra <ashish.kalra@amd.com>
11 #include <linux/cc_platform.h>
12 #include <linux/printk.h>
13 #include <linux/mm_types.h>
14 #include <linux/set_memory.h>
15 #include <linux/memblock.h>
16 #include <linux/kernel.h>
18 #include <linux/cpumask.h>
19 #include <linux/iommu.h>
20 #include <linux/amd-iommu.h>
23 #include <asm/processor.h>
24 #include <asm/setup.h>
29 #include <asm/cpuid.h>
30 #include <asm/cmdline.h>
31 #include <asm/iommu.h>
34 * The RMP entry format is not architectural. The format is defined in PPR
35 * Family 19h Model 01h, Rev B1 processor.
56 * The first 16KB from the RMP_BASE is used by the processor for the
57 * bookkeeping, the range needs to be added during the RMP entry lookup.
59 #define RMPTABLE_CPU_BOOKKEEPING_SZ 0x4000
61 /* Mask to apply to a PFN to get the first PFN of a 2MB page */
62 #define PFN_PMD_MASK GENMASK_ULL(63, PMD_SHIFT - PAGE_SHIFT)
64 static u64 probed_rmp_base, probed_rmp_size;
65 static struct rmpentry *rmptable __ro_after_init;
66 static u64 rmptable_max_pfn __ro_after_init;
68 static LIST_HEAD(snp_leaked_pages_list);
69 static DEFINE_SPINLOCK(snp_leaked_pages_list_lock);
71 static unsigned long snp_nr_leaked_pages;
74 #define pr_fmt(fmt) "SEV-SNP: " fmt
76 static int __mfd_enable(unsigned int cpu)
80 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
83 rdmsrl(MSR_AMD64_SYSCFG, val);
85 val |= MSR_AMD64_SYSCFG_MFDM;
87 wrmsrl(MSR_AMD64_SYSCFG, val);
92 static __init void mfd_enable(void *arg)
94 __mfd_enable(smp_processor_id());
97 static int __snp_enable(unsigned int cpu)
101 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
104 rdmsrl(MSR_AMD64_SYSCFG, val);
106 val |= MSR_AMD64_SYSCFG_SNP_EN;
107 val |= MSR_AMD64_SYSCFG_SNP_VMPL_EN;
109 wrmsrl(MSR_AMD64_SYSCFG, val);
114 static __init void snp_enable(void *arg)
116 __snp_enable(smp_processor_id());
119 #define RMP_ADDR_MASK GENMASK_ULL(51, 13)
121 bool snp_probe_rmptable_info(void)
123 u64 max_rmp_pfn, calc_rmp_sz, rmp_sz, rmp_base, rmp_end;
125 rdmsrl(MSR_AMD64_RMP_BASE, rmp_base);
126 rdmsrl(MSR_AMD64_RMP_END, rmp_end);
128 if (!(rmp_base & RMP_ADDR_MASK) || !(rmp_end & RMP_ADDR_MASK)) {
129 pr_err("Memory for the RMP table has not been reserved by BIOS\n");
133 if (rmp_base > rmp_end) {
134 pr_err("RMP configuration not valid: base=%#llx, end=%#llx\n", rmp_base, rmp_end);
138 rmp_sz = rmp_end - rmp_base + 1;
141 * Calculate the amount the memory that must be reserved by the BIOS to
142 * address the whole RAM, including the bookkeeping area. The RMP itself
143 * must also be covered.
145 max_rmp_pfn = max_pfn;
146 if (PHYS_PFN(rmp_end) > max_pfn)
147 max_rmp_pfn = PHYS_PFN(rmp_end);
149 calc_rmp_sz = (max_rmp_pfn << 4) + RMPTABLE_CPU_BOOKKEEPING_SZ;
151 if (calc_rmp_sz > rmp_sz) {
152 pr_err("Memory reserved for the RMP table does not cover full system RAM (expected 0x%llx got 0x%llx)\n",
153 calc_rmp_sz, rmp_sz);
157 probed_rmp_base = rmp_base;
158 probed_rmp_size = rmp_sz;
160 pr_info("RMP table physical range [0x%016llx - 0x%016llx]\n",
161 probed_rmp_base, probed_rmp_base + probed_rmp_size - 1);
167 * Do the necessary preparations which are verified by the firmware as
168 * described in the SNP_INIT_EX firmware command description in the SNP
171 static int __init snp_rmptable_init(void)
173 void *rmptable_start;
177 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
180 if (!amd_iommu_snp_en)
183 if (!probed_rmp_size)
186 rmptable_start = memremap(probed_rmp_base, probed_rmp_size, MEMREMAP_WB);
187 if (!rmptable_start) {
188 pr_err("Failed to map RMP table\n");
193 * Check if SEV-SNP is already enabled, this can happen in case of
196 rdmsrl(MSR_AMD64_SYSCFG, val);
197 if (val & MSR_AMD64_SYSCFG_SNP_EN)
200 memset(rmptable_start, 0, probed_rmp_size);
202 /* Flush the caches to ensure that data is written before SNP is enabled. */
203 wbinvd_on_all_cpus();
205 /* MtrrFixDramModEn must be enabled on all the CPUs prior to enabling SNP. */
206 on_each_cpu(mfd_enable, NULL, 1);
208 on_each_cpu(snp_enable, NULL, 1);
211 rmptable_start += RMPTABLE_CPU_BOOKKEEPING_SZ;
212 rmptable_size = probed_rmp_size - RMPTABLE_CPU_BOOKKEEPING_SZ;
214 rmptable = (struct rmpentry *)rmptable_start;
215 rmptable_max_pfn = rmptable_size / sizeof(struct rmpentry) - 1;
217 cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/rmptable_init:online", __snp_enable, NULL);
220 * Setting crash_kexec_post_notifiers to 'true' to ensure that SNP panic
221 * notifier is invoked to do SNP IOMMU shutdown before kdump.
223 crash_kexec_post_notifiers = true;
228 setup_clear_cpu_cap(X86_FEATURE_SEV_SNP);
233 * This must be called after the IOMMU has been initialized.
235 device_initcall(snp_rmptable_init);
237 static struct rmpentry *get_rmpentry(u64 pfn)
239 if (WARN_ON_ONCE(pfn > rmptable_max_pfn))
240 return ERR_PTR(-EFAULT);
242 return &rmptable[pfn];
245 static struct rmpentry *__snp_lookup_rmpentry(u64 pfn, int *level)
247 struct rmpentry *large_entry, *entry;
249 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
250 return ERR_PTR(-ENODEV);
252 entry = get_rmpentry(pfn);
257 * Find the authoritative RMP entry for a PFN. This can be either a 4K
258 * RMP entry or a special large RMP entry that is authoritative for a
261 large_entry = get_rmpentry(pfn & PFN_PMD_MASK);
262 if (IS_ERR(large_entry))
265 *level = RMP_TO_PG_LEVEL(large_entry->pagesize);
270 int snp_lookup_rmpentry(u64 pfn, bool *assigned, int *level)
274 e = __snp_lookup_rmpentry(pfn, level);
278 *assigned = !!e->assigned;
281 EXPORT_SYMBOL_GPL(snp_lookup_rmpentry);
284 * Dump the raw RMP entry for a particular PFN. These bits are documented in the
285 * PPR for a particular CPU model and provide useful information about how a
286 * particular PFN is being utilized by the kernel/firmware at the time certain
287 * unexpected events occur, such as RMP faults.
289 static void dump_rmpentry(u64 pfn)
295 e = __snp_lookup_rmpentry(pfn, &level);
297 pr_err("Failed to read RMP entry for PFN 0x%llx, error %ld\n",
303 pr_info("PFN 0x%llx, RMP entry: [0x%016llx - 0x%016llx]\n",
309 * If the RMP entry for a particular PFN is not in an assigned state,
310 * then it is sometimes useful to get an idea of whether or not any RMP
311 * entries for other PFNs within the same 2MB region are assigned, since
312 * those too can affect the ability to access a particular PFN in
313 * certain situations, such as when the PFN is being accessed via a 2MB
314 * mapping in the host page table.
316 pfn_i = ALIGN_DOWN(pfn, PTRS_PER_PMD);
317 pfn_end = pfn_i + PTRS_PER_PMD;
319 pr_info("PFN 0x%llx unassigned, dumping non-zero entries in 2M PFN region: [0x%llx - 0x%llx]\n",
320 pfn, pfn_i, pfn_end);
322 while (pfn_i < pfn_end) {
323 e = __snp_lookup_rmpentry(pfn_i, &level);
325 pr_err("Error %ld reading RMP entry for PFN 0x%llx\n",
332 pr_info("PFN: 0x%llx, [0x%016llx - 0x%016llx]\n", pfn_i, e->lo, e->hi);
337 void snp_dump_hva_rmpentry(unsigned long hva)
344 pgd = __va(read_cr3_pa());
345 pgd += pgd_index(hva);
346 pte = lookup_address_in_pgd(pgd, hva, &level);
349 pr_err("Can't dump RMP entry for HVA %lx: no PTE/PFN found\n", hva);
353 paddr = PFN_PHYS(pte_pfn(*pte)) | (hva & ~page_level_mask(level));
354 dump_rmpentry(PHYS_PFN(paddr));
358 * PSMASH a 2MB aligned page into 4K pages in the RMP table while preserving the
363 unsigned long paddr = pfn << PAGE_SHIFT;
366 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
372 /* Binutils version 2.36 supports the PSMASH mnemonic. */
373 asm volatile(".byte 0xF3, 0x0F, 0x01, 0xFF"
380 EXPORT_SYMBOL_GPL(psmash);
383 * If the kernel uses a 2MB or larger directmap mapping to write to an address,
384 * and that mapping contains any 4KB pages that are set to private in the RMP
385 * table, an RMP #PF will trigger and cause a host crash. Hypervisor code that
386 * owns the PFNs being transitioned will never attempt such a write, but other
387 * kernel tasks writing to other PFNs in the range may trigger these checks
388 * inadvertently due a large directmap mapping that happens to overlap such a
391 * Prevent this by splitting any 2MB+ mappings that might end up containing a
392 * mix of private/shared PFNs as a result of a subsequent RMPUPDATE for the
393 * PFN/rmp_level passed in.
395 * Note that there is no attempt here to scan all the RMP entries for the 2MB
396 * physical range, since it would only be worthwhile in determining if a
397 * subsequent RMPUPDATE for a 4KB PFN would result in all the entries being of
398 * the same shared/private state, thus avoiding the need to split the mapping.
399 * But that would mean the entries are currently in a mixed state, and so the
400 * mapping would have already been split as a result of prior transitions.
401 * And since the 4K split is only done if the mapping is 2MB+, and there isn't
402 * currently a mechanism in place to restore 2MB+ mappings, such a check would
403 * not provide any usable benefit.
405 * More specifics on how these checks are carried out can be found in APM
406 * Volume 2, "RMP and VMPL Access Checks".
408 static int adjust_direct_map(u64 pfn, int rmp_level)
416 * pfn_to_kaddr() will return a vaddr only within the direct
419 vaddr = (unsigned long)pfn_to_kaddr(pfn);
421 /* Only 4KB/2MB RMP entries are supported by current hardware. */
422 if (WARN_ON_ONCE(rmp_level > PG_LEVEL_2M))
428 if (rmp_level == PG_LEVEL_2M &&
429 (!IS_ALIGNED(pfn, PTRS_PER_PMD) || !pfn_valid(pfn + PTRS_PER_PMD - 1)))
433 * If an entire 2MB physical range is being transitioned, then there is
434 * no risk of RMP #PFs due to write accesses from overlapping mappings,
435 * since even accesses from 1GB mappings will be treated as 2MB accesses
436 * as far as RMP table checks are concerned.
438 if (rmp_level == PG_LEVEL_2M)
441 pte = lookup_address(vaddr, &level);
442 if (!pte || pte_none(*pte))
445 if (level == PG_LEVEL_4K)
448 npages = page_level_size(rmp_level) / PAGE_SIZE;
449 ret = set_memory_4k(vaddr, npages);
451 pr_warn("Failed to split direct map for PFN 0x%llx, ret: %d\n",
458 * It is expected that those operations are seldom enough so that no mutual
459 * exclusion of updaters is needed and thus the overlap error condition below
460 * should happen very rarely and would get resolved relatively quickly by
463 * If not, one could consider introducing a mutex or so here to sync concurrent
464 * RMP updates and thus diminish the amount of cases where firmware needs to
465 * lock 2M ranges to protect against concurrent updates.
467 * The optimal solution would be range locking to avoid locking disjoint
468 * regions unnecessarily but there's no support for that yet.
470 static int rmpupdate(u64 pfn, struct rmp_state *state)
472 unsigned long paddr = pfn << PAGE_SHIFT;
475 if (!cpu_feature_enabled(X86_FEATURE_SEV_SNP))
478 level = RMP_TO_PG_LEVEL(state->pagesize);
480 if (adjust_direct_map(pfn, level))
484 /* Binutils version 2.36 supports the RMPUPDATE mnemonic. */
485 asm volatile(".byte 0xF2, 0x0F, 0x01, 0xFE"
487 : "a" (paddr), "c" ((unsigned long)state)
489 } while (ret == RMPUPDATE_FAIL_OVERLAP);
492 pr_err("RMPUPDATE failed for PFN %llx, pg_level: %d, ret: %d\n",
502 /* Transition a page to guest-owned/private state in the RMP table. */
503 int rmp_make_private(u64 pfn, u64 gpa, enum pg_level level, u32 asid, bool immutable)
505 struct rmp_state state;
507 memset(&state, 0, sizeof(state));
510 state.immutable = immutable;
512 state.pagesize = PG_LEVEL_TO_RMP(level);
514 return rmpupdate(pfn, &state);
516 EXPORT_SYMBOL_GPL(rmp_make_private);
518 /* Transition a page to hypervisor-owned/shared state in the RMP table. */
519 int rmp_make_shared(u64 pfn, enum pg_level level)
521 struct rmp_state state;
523 memset(&state, 0, sizeof(state));
524 state.pagesize = PG_LEVEL_TO_RMP(level);
526 return rmpupdate(pfn, &state);
528 EXPORT_SYMBOL_GPL(rmp_make_shared);
530 void snp_leak_pages(u64 pfn, unsigned int npages)
532 struct page *page = pfn_to_page(pfn);
534 pr_warn("Leaking PFN range 0x%llx-0x%llx\n", pfn, pfn + npages);
536 spin_lock(&snp_leaked_pages_list_lock);
540 * Reuse the page's buddy list for chaining into the leaked
541 * pages list. This page should not be on a free list currently
542 * and is also unsafe to be added to a free list.
544 if (likely(!PageCompound(page)) ||
547 * Skip inserting tail pages of compound page as
548 * page->buddy_list of tail pages is not usable.
550 (PageHead(page) && compound_nr(page) <= npages))
551 list_add_tail(&page->buddy_list, &snp_leaked_pages_list);
554 snp_nr_leaked_pages++;
558 spin_unlock(&snp_leaked_pages_list_lock);
560 EXPORT_SYMBOL_GPL(snp_leak_pages);