xref: /linux/arch/x86/virt/svm/sev.c (revision 5d6ba5ab8582aa35c1ee98e47af28e6f6772596c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AMD SVM-SEV Host Support.
4  *
5  * Copyright (C) 2023 Advanced Micro Devices, Inc.
6  *
7  * Author: Ashish Kalra <ashish.kalra@amd.com>
8  *
9  */
10 
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>
17 #include <linux/mm.h>
18 #include <linux/cpumask.h>
19 #include <linux/iommu.h>
20 #include <linux/amd-iommu.h>
21 #include <linux/nospec.h>
22 
23 #include <asm/sev.h>
24 #include <asm/processor.h>
25 #include <asm/setup.h>
26 #include <asm/svm.h>
27 #include <asm/smp.h>
28 #include <asm/cpu.h>
29 #include <asm/apic.h>
30 #include <asm/cpuid.h>
31 #include <asm/cmdline.h>
32 #include <asm/iommu.h>
33 
34 /*
35  * The RMP entry information as returned by the RMPREAD instruction.
36  */
37 struct rmpentry {
38 	u64 gpa;
39 	u8  assigned		:1,
40 	    rsvd1		:7;
41 	u8  pagesize		:1,
42 	    hpage_region_status	:1,
43 	    rsvd2		:6;
44 	u8  immutable		:1,
45 	    rsvd3		:7;
46 	u8  rsvd4;
47 	u32 asid;
48 } __packed;
49 
50 /*
51  * The raw RMP entry format is not architectural. The format is defined in PPR
52  * Family 19h Model 01h, Rev B1 processor. This format represents the actual
53  * entry in the RMP table memory. The bitfield definitions are used for machines
54  * without the RMPREAD instruction (Zen3 and Zen4), otherwise the "hi" and "lo"
55  * fields are only used for dumping the raw data.
56  */
57 struct rmpentry_raw {
58 	union {
59 		struct {
60 			u64 assigned	: 1,
61 			    pagesize	: 1,
62 			    immutable	: 1,
63 			    rsvd1	: 9,
64 			    gpa		: 39,
65 			    asid	: 10,
66 			    vmsa	: 1,
67 			    validated	: 1,
68 			    rsvd2	: 1;
69 		};
70 		u64 lo;
71 	};
72 	u64 hi;
73 } __packed;
74 
75 /*
76  * The first 16KB from the RMP_BASE is used by the processor for the
77  * bookkeeping, the range needs to be added during the RMP entry lookup.
78  */
79 #define RMPTABLE_CPU_BOOKKEEPING_SZ	0x4000
80 
81 /*
82  * For a non-segmented RMP table, use the maximum physical addressing as the
83  * segment size in order to always arrive at index 0 in the table.
84  */
85 #define RMPTABLE_NON_SEGMENTED_SHIFT	52
86 
87 struct rmp_segment_desc {
88 	struct rmpentry_raw *rmp_entry;
89 	u64 max_index;
90 	u64 size;
91 };
92 
93 /*
94  * Segmented RMP Table support.
95  *   - The segment size is used for two purposes:
96  *     - Identify the amount of memory covered by an RMP segment
97  *     - Quickly locate an RMP segment table entry for a physical address
98  *
99  *   - The RMP segment table contains pointers to an RMP table that covers
100  *     a specific portion of memory. There can be up to 512 8-byte entries,
101  *     one pages worth.
102  */
103 #define RST_ENTRY_MAPPED_SIZE(x)	((x) & GENMASK_ULL(19, 0))
104 #define RST_ENTRY_SEGMENT_BASE(x)	((x) & GENMASK_ULL(51, 20))
105 
106 #define RST_SIZE SZ_4K
107 static struct rmp_segment_desc **rmp_segment_table __ro_after_init;
108 static unsigned int rst_max_index __ro_after_init = 512;
109 
110 static unsigned int rmp_segment_shift;
111 static u64 rmp_segment_size;
112 static u64 rmp_segment_mask;
113 
114 #define RST_ENTRY_INDEX(x)	((x) >> rmp_segment_shift)
115 #define RMP_ENTRY_INDEX(x)	((u64)(PHYS_PFN((x) & rmp_segment_mask)))
116 
117 static u64 rmp_cfg;
118 
119 /* Mask to apply to a PFN to get the first PFN of a 2MB page */
120 #define PFN_PMD_MASK	GENMASK_ULL(63, PMD_SHIFT - PAGE_SHIFT)
121 
122 static u64 probed_rmp_base, probed_rmp_size;
123 
124 static LIST_HEAD(snp_leaked_pages_list);
125 static DEFINE_SPINLOCK(snp_leaked_pages_list_lock);
126 
127 static unsigned long snp_nr_leaked_pages;
128 
129 #undef pr_fmt
130 #define pr_fmt(fmt)	"SEV-SNP: " fmt
131 
__mfd_enable(unsigned int cpu)132 static int __mfd_enable(unsigned int cpu)
133 {
134 	u64 val;
135 
136 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
137 		return 0;
138 
139 	rdmsrl(MSR_AMD64_SYSCFG, val);
140 
141 	val |= MSR_AMD64_SYSCFG_MFDM;
142 
143 	wrmsrl(MSR_AMD64_SYSCFG, val);
144 
145 	return 0;
146 }
147 
mfd_enable(void * arg)148 static __init void mfd_enable(void *arg)
149 {
150 	__mfd_enable(smp_processor_id());
151 }
152 
__snp_enable(unsigned int cpu)153 static int __snp_enable(unsigned int cpu)
154 {
155 	u64 val;
156 
157 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
158 		return 0;
159 
160 	rdmsrl(MSR_AMD64_SYSCFG, val);
161 
162 	val |= MSR_AMD64_SYSCFG_SNP_EN;
163 	val |= MSR_AMD64_SYSCFG_SNP_VMPL_EN;
164 
165 	wrmsrl(MSR_AMD64_SYSCFG, val);
166 
167 	return 0;
168 }
169 
snp_enable(void * arg)170 static __init void snp_enable(void *arg)
171 {
172 	__snp_enable(smp_processor_id());
173 }
174 
__snp_fixup_e820_tables(u64 pa)175 static void __init __snp_fixup_e820_tables(u64 pa)
176 {
177 	if (IS_ALIGNED(pa, PMD_SIZE))
178 		return;
179 
180 	/*
181 	 * Handle cases where the RMP table placement by the BIOS is not
182 	 * 2M aligned and the kexec kernel could try to allocate
183 	 * from within that chunk which then causes a fatal RMP fault.
184 	 *
185 	 * The e820_table needs to be updated as it is converted to
186 	 * kernel memory resources and used by KEXEC_FILE_LOAD syscall
187 	 * to load kexec segments.
188 	 *
189 	 * The e820_table_firmware needs to be updated as it is exposed
190 	 * to sysfs and used by the KEXEC_LOAD syscall to load kexec
191 	 * segments.
192 	 *
193 	 * The e820_table_kexec needs to be updated as it passed to
194 	 * the kexec-ed kernel.
195 	 */
196 	pa = ALIGN_DOWN(pa, PMD_SIZE);
197 	if (e820__mapped_any(pa, pa + PMD_SIZE, E820_TYPE_RAM)) {
198 		pr_info("Reserving start/end of RMP table on a 2MB boundary [0x%016llx]\n", pa);
199 		e820__range_update(pa, PMD_SIZE, E820_TYPE_RAM, E820_TYPE_RESERVED);
200 		e820__range_update_table(e820_table_kexec, pa, PMD_SIZE, E820_TYPE_RAM, E820_TYPE_RESERVED);
201 		if (!memblock_is_region_reserved(pa, PMD_SIZE))
202 			memblock_reserve(pa, PMD_SIZE);
203 	}
204 }
205 
fixup_e820_tables_for_segmented_rmp(void)206 static void __init fixup_e820_tables_for_segmented_rmp(void)
207 {
208 	u64 pa, *rst, size, mapped_size;
209 	unsigned int i;
210 
211 	__snp_fixup_e820_tables(probed_rmp_base);
212 
213 	pa = probed_rmp_base + RMPTABLE_CPU_BOOKKEEPING_SZ;
214 
215 	__snp_fixup_e820_tables(pa + RST_SIZE);
216 
217 	rst = early_memremap(pa, RST_SIZE);
218 	if (!rst)
219 		return;
220 
221 	for (i = 0; i < rst_max_index; i++) {
222 		pa = RST_ENTRY_SEGMENT_BASE(rst[i]);
223 		mapped_size = RST_ENTRY_MAPPED_SIZE(rst[i]);
224 		if (!mapped_size)
225 			continue;
226 
227 		__snp_fixup_e820_tables(pa);
228 
229 		/*
230 		 * Mapped size in GB. Mapped size is allowed to exceed
231 		 * the segment coverage size, but gets reduced to the
232 		 * segment coverage size.
233 		 */
234 		mapped_size <<= 30;
235 		if (mapped_size > rmp_segment_size)
236 			mapped_size = rmp_segment_size;
237 
238 		/* Calculate the RMP segment size (16 bytes/page mapped) */
239 		size = PHYS_PFN(mapped_size) << 4;
240 
241 		__snp_fixup_e820_tables(pa + size);
242 	}
243 
244 	early_memunmap(rst, RST_SIZE);
245 }
246 
fixup_e820_tables_for_contiguous_rmp(void)247 static void __init fixup_e820_tables_for_contiguous_rmp(void)
248 {
249 	__snp_fixup_e820_tables(probed_rmp_base);
250 	__snp_fixup_e820_tables(probed_rmp_base + probed_rmp_size);
251 }
252 
snp_fixup_e820_tables(void)253 void __init snp_fixup_e820_tables(void)
254 {
255 	if (rmp_cfg & MSR_AMD64_SEG_RMP_ENABLED) {
256 		fixup_e820_tables_for_segmented_rmp();
257 	} else {
258 		fixup_e820_tables_for_contiguous_rmp();
259 	}
260 }
261 
clear_rmptable_bookkeeping(void)262 static bool __init clear_rmptable_bookkeeping(void)
263 {
264 	void *bk;
265 
266 	bk = memremap(probed_rmp_base, RMPTABLE_CPU_BOOKKEEPING_SZ, MEMREMAP_WB);
267 	if (!bk) {
268 		pr_err("Failed to map RMP bookkeeping area\n");
269 		return false;
270 	}
271 
272 	memset(bk, 0, RMPTABLE_CPU_BOOKKEEPING_SZ);
273 
274 	memunmap(bk);
275 
276 	return true;
277 }
278 
alloc_rmp_segment_desc(u64 segment_pa,u64 segment_size,u64 pa)279 static bool __init alloc_rmp_segment_desc(u64 segment_pa, u64 segment_size, u64 pa)
280 {
281 	u64 rst_index, rmp_segment_size_max;
282 	struct rmp_segment_desc *desc;
283 	void *rmp_segment;
284 
285 	/* Calculate the maximum size an RMP can be (16 bytes/page mapped) */
286 	rmp_segment_size_max = PHYS_PFN(rmp_segment_size) << 4;
287 
288 	/* Validate the RMP segment size */
289 	if (segment_size > rmp_segment_size_max) {
290 		pr_err("Invalid RMP size 0x%llx for configured segment size 0x%llx\n",
291 		       segment_size, rmp_segment_size_max);
292 		return false;
293 	}
294 
295 	/* Validate the RMP segment table index */
296 	rst_index = RST_ENTRY_INDEX(pa);
297 	if (rst_index >= rst_max_index) {
298 		pr_err("Invalid RMP segment base address 0x%llx for configured segment size 0x%llx\n",
299 		       pa, rmp_segment_size);
300 		return false;
301 	}
302 
303 	if (rmp_segment_table[rst_index]) {
304 		pr_err("RMP segment descriptor already exists at index %llu\n", rst_index);
305 		return false;
306 	}
307 
308 	rmp_segment = memremap(segment_pa, segment_size, MEMREMAP_WB);
309 	if (!rmp_segment) {
310 		pr_err("Failed to map RMP segment addr 0x%llx size 0x%llx\n",
311 		       segment_pa, segment_size);
312 		return false;
313 	}
314 
315 	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
316 	if (!desc) {
317 		memunmap(rmp_segment);
318 		return false;
319 	}
320 
321 	desc->rmp_entry = rmp_segment;
322 	desc->max_index = segment_size / sizeof(*desc->rmp_entry);
323 	desc->size = segment_size;
324 
325 	rmp_segment_table[rst_index] = desc;
326 
327 	return true;
328 }
329 
free_rmp_segment_table(void)330 static void __init free_rmp_segment_table(void)
331 {
332 	unsigned int i;
333 
334 	for (i = 0; i < rst_max_index; i++) {
335 		struct rmp_segment_desc *desc;
336 
337 		desc = rmp_segment_table[i];
338 		if (!desc)
339 			continue;
340 
341 		memunmap(desc->rmp_entry);
342 
343 		kfree(desc);
344 	}
345 
346 	free_page((unsigned long)rmp_segment_table);
347 
348 	rmp_segment_table = NULL;
349 }
350 
351 /* Allocate the table used to index into the RMP segments */
alloc_rmp_segment_table(void)352 static bool __init alloc_rmp_segment_table(void)
353 {
354 	struct page *page;
355 
356 	page = alloc_page(__GFP_ZERO);
357 	if (!page)
358 		return false;
359 
360 	rmp_segment_table = page_address(page);
361 
362 	return true;
363 }
364 
setup_contiguous_rmptable(void)365 static bool __init setup_contiguous_rmptable(void)
366 {
367 	u64 max_rmp_pfn, calc_rmp_sz, rmptable_segment, rmptable_size, rmp_end;
368 
369 	if (!probed_rmp_size)
370 		return false;
371 
372 	rmp_end = probed_rmp_base + probed_rmp_size - 1;
373 
374 	/*
375 	 * Calculate the amount of memory that must be reserved by the BIOS to
376 	 * address the whole RAM, including the bookkeeping area. The RMP itself
377 	 * must also be covered.
378 	 */
379 	max_rmp_pfn = max_pfn;
380 	if (PFN_UP(rmp_end) > max_pfn)
381 		max_rmp_pfn = PFN_UP(rmp_end);
382 
383 	calc_rmp_sz = (max_rmp_pfn << 4) + RMPTABLE_CPU_BOOKKEEPING_SZ;
384 	if (calc_rmp_sz > probed_rmp_size) {
385 		pr_err("Memory reserved for the RMP table does not cover full system RAM (expected 0x%llx got 0x%llx)\n",
386 		       calc_rmp_sz, probed_rmp_size);
387 		return false;
388 	}
389 
390 	if (!alloc_rmp_segment_table())
391 		return false;
392 
393 	/* Map only the RMP entries */
394 	rmptable_segment = probed_rmp_base + RMPTABLE_CPU_BOOKKEEPING_SZ;
395 	rmptable_size    = probed_rmp_size - RMPTABLE_CPU_BOOKKEEPING_SZ;
396 
397 	if (!alloc_rmp_segment_desc(rmptable_segment, rmptable_size, 0)) {
398 		free_rmp_segment_table();
399 		return false;
400 	}
401 
402 	return true;
403 }
404 
setup_segmented_rmptable(void)405 static bool __init setup_segmented_rmptable(void)
406 {
407 	u64 rst_pa, *rst, pa, ram_pa_end, ram_pa_max;
408 	unsigned int i, max_index;
409 
410 	if (!probed_rmp_base)
411 		return false;
412 
413 	if (!alloc_rmp_segment_table())
414 		return false;
415 
416 	rst_pa = probed_rmp_base + RMPTABLE_CPU_BOOKKEEPING_SZ;
417 	rst = memremap(rst_pa, RST_SIZE, MEMREMAP_WB);
418 	if (!rst) {
419 		pr_err("Failed to map RMP segment table addr 0x%llx\n", rst_pa);
420 		goto e_free;
421 	}
422 
423 	pr_info("Segmented RMP using %lluGB segments\n", rmp_segment_size >> 30);
424 
425 	ram_pa_max = max_pfn << PAGE_SHIFT;
426 
427 	max_index = 0;
428 	ram_pa_end = 0;
429 	for (i = 0; i < rst_max_index; i++) {
430 		u64 rmp_segment, rmp_size, mapped_size;
431 
432 		mapped_size = RST_ENTRY_MAPPED_SIZE(rst[i]);
433 		if (!mapped_size)
434 			continue;
435 
436 		max_index = i;
437 
438 		/*
439 		 * Mapped size in GB. Mapped size is allowed to exceed the
440 		 * segment coverage size, but gets reduced to the segment
441 		 * coverage size.
442 		 */
443 		mapped_size <<= 30;
444 		if (mapped_size > rmp_segment_size) {
445 			pr_info("RMP segment %u mapped size (0x%llx) reduced to 0x%llx\n",
446 				i, mapped_size, rmp_segment_size);
447 			mapped_size = rmp_segment_size;
448 		}
449 
450 		rmp_segment = RST_ENTRY_SEGMENT_BASE(rst[i]);
451 
452 		/* Calculate the RMP segment size (16 bytes/page mapped) */
453 		rmp_size = PHYS_PFN(mapped_size) << 4;
454 
455 		pa = (u64)i << rmp_segment_shift;
456 
457 		/*
458 		 * Some segments may be for MMIO mapped above system RAM. These
459 		 * segments are used for Trusted I/O.
460 		 */
461 		if (pa < ram_pa_max)
462 			ram_pa_end = pa + mapped_size;
463 
464 		if (!alloc_rmp_segment_desc(rmp_segment, rmp_size, pa))
465 			goto e_unmap;
466 
467 		pr_info("RMP segment %u physical address [0x%llx - 0x%llx] covering [0x%llx - 0x%llx]\n",
468 			i, rmp_segment, rmp_segment + rmp_size - 1, pa, pa + mapped_size - 1);
469 	}
470 
471 	if (ram_pa_max > ram_pa_end) {
472 		pr_err("Segmented RMP does not cover full system RAM (expected 0x%llx got 0x%llx)\n",
473 		       ram_pa_max, ram_pa_end);
474 		goto e_unmap;
475 	}
476 
477 	/* Adjust the maximum index based on the found segments */
478 	rst_max_index = max_index + 1;
479 
480 	memunmap(rst);
481 
482 	return true;
483 
484 e_unmap:
485 	memunmap(rst);
486 
487 e_free:
488 	free_rmp_segment_table();
489 
490 	return false;
491 }
492 
setup_rmptable(void)493 static bool __init setup_rmptable(void)
494 {
495 	if (rmp_cfg & MSR_AMD64_SEG_RMP_ENABLED) {
496 		return setup_segmented_rmptable();
497 	} else {
498 		return setup_contiguous_rmptable();
499 	}
500 }
501 
502 /*
503  * Do the necessary preparations which are verified by the firmware as
504  * described in the SNP_INIT_EX firmware command description in the SNP
505  * firmware ABI spec.
506  */
snp_rmptable_init(void)507 int __init snp_rmptable_init(void)
508 {
509 	unsigned int i;
510 	u64 val;
511 
512 	if (WARN_ON_ONCE(!cc_platform_has(CC_ATTR_HOST_SEV_SNP)))
513 		return -ENOSYS;
514 
515 	if (WARN_ON_ONCE(!amd_iommu_snp_en))
516 		return -ENOSYS;
517 
518 	if (!setup_rmptable())
519 		return -ENOSYS;
520 
521 	/*
522 	 * Check if SEV-SNP is already enabled, this can happen in case of
523 	 * kexec boot.
524 	 */
525 	rdmsrl(MSR_AMD64_SYSCFG, val);
526 	if (val & MSR_AMD64_SYSCFG_SNP_EN)
527 		goto skip_enable;
528 
529 	/* Zero out the RMP bookkeeping area */
530 	if (!clear_rmptable_bookkeeping()) {
531 		free_rmp_segment_table();
532 		return -ENOSYS;
533 	}
534 
535 	/* Zero out the RMP entries */
536 	for (i = 0; i < rst_max_index; i++) {
537 		struct rmp_segment_desc *desc;
538 
539 		desc = rmp_segment_table[i];
540 		if (!desc)
541 			continue;
542 
543 		memset(desc->rmp_entry, 0, desc->size);
544 	}
545 
546 	/* Flush the caches to ensure that data is written before SNP is enabled. */
547 	wbinvd_on_all_cpus();
548 
549 	/* MtrrFixDramModEn must be enabled on all the CPUs prior to enabling SNP. */
550 	on_each_cpu(mfd_enable, NULL, 1);
551 
552 	on_each_cpu(snp_enable, NULL, 1);
553 
554 skip_enable:
555 	cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/rmptable_init:online", __snp_enable, NULL);
556 
557 	/*
558 	 * Setting crash_kexec_post_notifiers to 'true' to ensure that SNP panic
559 	 * notifier is invoked to do SNP IOMMU shutdown before kdump.
560 	 */
561 	crash_kexec_post_notifiers = true;
562 
563 	return 0;
564 }
565 
set_rmp_segment_info(unsigned int segment_shift)566 static void set_rmp_segment_info(unsigned int segment_shift)
567 {
568 	rmp_segment_shift = segment_shift;
569 	rmp_segment_size  = 1ULL << rmp_segment_shift;
570 	rmp_segment_mask  = rmp_segment_size - 1;
571 }
572 
573 #define RMP_ADDR_MASK GENMASK_ULL(51, 13)
574 
probe_contiguous_rmptable_info(void)575 static bool probe_contiguous_rmptable_info(void)
576 {
577 	u64 rmp_sz, rmp_base, rmp_end;
578 
579 	rdmsrl(MSR_AMD64_RMP_BASE, rmp_base);
580 	rdmsrl(MSR_AMD64_RMP_END, rmp_end);
581 
582 	if (!(rmp_base & RMP_ADDR_MASK) || !(rmp_end & RMP_ADDR_MASK)) {
583 		pr_err("Memory for the RMP table has not been reserved by BIOS\n");
584 		return false;
585 	}
586 
587 	if (rmp_base > rmp_end) {
588 		pr_err("RMP configuration not valid: base=%#llx, end=%#llx\n", rmp_base, rmp_end);
589 		return false;
590 	}
591 
592 	rmp_sz = rmp_end - rmp_base + 1;
593 
594 	/* Treat the contiguous RMP table as a single segment */
595 	rst_max_index = 1;
596 
597 	set_rmp_segment_info(RMPTABLE_NON_SEGMENTED_SHIFT);
598 
599 	probed_rmp_base = rmp_base;
600 	probed_rmp_size = rmp_sz;
601 
602 	pr_info("RMP table physical range [0x%016llx - 0x%016llx]\n",
603 		rmp_base, rmp_end);
604 
605 	return true;
606 }
607 
probe_segmented_rmptable_info(void)608 static bool probe_segmented_rmptable_info(void)
609 {
610 	unsigned int eax, ebx, segment_shift, segment_shift_min, segment_shift_max;
611 	u64 rmp_base, rmp_end;
612 
613 	rdmsrl(MSR_AMD64_RMP_BASE, rmp_base);
614 	if (!(rmp_base & RMP_ADDR_MASK)) {
615 		pr_err("Memory for the RMP table has not been reserved by BIOS\n");
616 		return false;
617 	}
618 
619 	rdmsrl(MSR_AMD64_RMP_END, rmp_end);
620 	WARN_ONCE(rmp_end & RMP_ADDR_MASK,
621 		  "Segmented RMP enabled but RMP_END MSR is non-zero\n");
622 
623 	/* Obtain the min and max supported RMP segment size */
624 	eax = cpuid_eax(0x80000025);
625 	segment_shift_min = eax & GENMASK(5, 0);
626 	segment_shift_max = (eax & GENMASK(11, 6)) >> 6;
627 
628 	/* Verify the segment size is within the supported limits */
629 	segment_shift = MSR_AMD64_RMP_SEGMENT_SHIFT(rmp_cfg);
630 	if (segment_shift > segment_shift_max || segment_shift < segment_shift_min) {
631 		pr_err("RMP segment size (%u) is not within advertised bounds (min=%u, max=%u)\n",
632 		       segment_shift, segment_shift_min, segment_shift_max);
633 		return false;
634 	}
635 
636 	/* Override the max supported RST index if a hardware limit exists */
637 	ebx = cpuid_ebx(0x80000025);
638 	if (ebx & BIT(10))
639 		rst_max_index = ebx & GENMASK(9, 0);
640 
641 	set_rmp_segment_info(segment_shift);
642 
643 	probed_rmp_base = rmp_base;
644 	probed_rmp_size = 0;
645 
646 	pr_info("Segmented RMP base table physical range [0x%016llx - 0x%016llx]\n",
647 		rmp_base, rmp_base + RMPTABLE_CPU_BOOKKEEPING_SZ + RST_SIZE);
648 
649 	return true;
650 }
651 
snp_probe_rmptable_info(void)652 bool snp_probe_rmptable_info(void)
653 {
654 	if (cpu_feature_enabled(X86_FEATURE_SEGMENTED_RMP))
655 		rdmsrl(MSR_AMD64_RMP_CFG, rmp_cfg);
656 
657 	if (rmp_cfg & MSR_AMD64_SEG_RMP_ENABLED)
658 		return probe_segmented_rmptable_info();
659 	else
660 		return probe_contiguous_rmptable_info();
661 }
662 
663 /*
664  * About the array_index_nospec() usage below:
665  *
666  * This function can get called by exported functions like
667  * snp_lookup_rmpentry(), which is used by the KVM #PF handler, among
668  * others, and since the @pfn passed in cannot always be trusted,
669  * speculation should be stopped as a protective measure.
670  */
get_raw_rmpentry(u64 pfn)671 static struct rmpentry_raw *get_raw_rmpentry(u64 pfn)
672 {
673 	u64 paddr, rst_index, segment_index;
674 	struct rmp_segment_desc *desc;
675 
676 	if (!rmp_segment_table)
677 		return ERR_PTR(-ENODEV);
678 
679 	paddr = pfn << PAGE_SHIFT;
680 
681 	rst_index = RST_ENTRY_INDEX(paddr);
682 	if (unlikely(rst_index >= rst_max_index))
683 		return ERR_PTR(-EFAULT);
684 
685 	rst_index = array_index_nospec(rst_index, rst_max_index);
686 
687 	desc = rmp_segment_table[rst_index];
688 	if (unlikely(!desc))
689 		return ERR_PTR(-EFAULT);
690 
691 	segment_index = RMP_ENTRY_INDEX(paddr);
692 	if (unlikely(segment_index >= desc->max_index))
693 		return ERR_PTR(-EFAULT);
694 
695 	segment_index = array_index_nospec(segment_index, desc->max_index);
696 
697 	return desc->rmp_entry + segment_index;
698 }
699 
get_rmpentry(u64 pfn,struct rmpentry * e)700 static int get_rmpentry(u64 pfn, struct rmpentry *e)
701 {
702 	struct rmpentry_raw *e_raw;
703 
704 	if (cpu_feature_enabled(X86_FEATURE_RMPREAD)) {
705 		int ret;
706 
707 		/* Binutils version 2.44 supports the RMPREAD mnemonic. */
708 		asm volatile(".byte 0xf2, 0x0f, 0x01, 0xfd"
709 			     : "=a" (ret)
710 			     : "a" (pfn << PAGE_SHIFT), "c" (e)
711 			     : "memory", "cc");
712 
713 		return ret;
714 	}
715 
716 	e_raw = get_raw_rmpentry(pfn);
717 	if (IS_ERR(e_raw))
718 		return PTR_ERR(e_raw);
719 
720 	/*
721 	 * Map the raw RMP table entry onto the RMPREAD output format.
722 	 * The 2MB region status indicator (hpage_region_status field) is not
723 	 * calculated, since the overhead could be significant and the field
724 	 * is not used.
725 	 */
726 	memset(e, 0, sizeof(*e));
727 	e->gpa       = e_raw->gpa << PAGE_SHIFT;
728 	e->asid      = e_raw->asid;
729 	e->assigned  = e_raw->assigned;
730 	e->pagesize  = e_raw->pagesize;
731 	e->immutable = e_raw->immutable;
732 
733 	return 0;
734 }
735 
__snp_lookup_rmpentry(u64 pfn,struct rmpentry * e,int * level)736 static int __snp_lookup_rmpentry(u64 pfn, struct rmpentry *e, int *level)
737 {
738 	struct rmpentry e_large;
739 	int ret;
740 
741 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
742 		return -ENODEV;
743 
744 	ret = get_rmpentry(pfn, e);
745 	if (ret)
746 		return ret;
747 
748 	/*
749 	 * Find the authoritative RMP entry for a PFN. This can be either a 4K
750 	 * RMP entry or a special large RMP entry that is authoritative for a
751 	 * whole 2M area.
752 	 */
753 	ret = get_rmpentry(pfn & PFN_PMD_MASK, &e_large);
754 	if (ret)
755 		return ret;
756 
757 	*level = RMP_TO_PG_LEVEL(e_large.pagesize);
758 
759 	return 0;
760 }
761 
snp_lookup_rmpentry(u64 pfn,bool * assigned,int * level)762 int snp_lookup_rmpentry(u64 pfn, bool *assigned, int *level)
763 {
764 	struct rmpentry e;
765 	int ret;
766 
767 	ret = __snp_lookup_rmpentry(pfn, &e, level);
768 	if (ret)
769 		return ret;
770 
771 	*assigned = !!e.assigned;
772 	return 0;
773 }
774 EXPORT_SYMBOL_GPL(snp_lookup_rmpentry);
775 
776 /*
777  * Dump the raw RMP entry for a particular PFN. These bits are documented in the
778  * PPR for a particular CPU model and provide useful information about how a
779  * particular PFN is being utilized by the kernel/firmware at the time certain
780  * unexpected events occur, such as RMP faults.
781  */
dump_rmpentry(u64 pfn)782 static void dump_rmpentry(u64 pfn)
783 {
784 	struct rmpentry_raw *e_raw;
785 	u64 pfn_i, pfn_end;
786 	struct rmpentry e;
787 	int level, ret;
788 
789 	ret = __snp_lookup_rmpentry(pfn, &e, &level);
790 	if (ret) {
791 		pr_err("Failed to read RMP entry for PFN 0x%llx, error %d\n",
792 		       pfn, ret);
793 		return;
794 	}
795 
796 	if (e.assigned) {
797 		e_raw = get_raw_rmpentry(pfn);
798 		if (IS_ERR(e_raw)) {
799 			pr_err("Failed to read RMP contents for PFN 0x%llx, error %ld\n",
800 			       pfn, PTR_ERR(e_raw));
801 			return;
802 		}
803 
804 		pr_info("PFN 0x%llx, RMP entry: [0x%016llx - 0x%016llx]\n",
805 			pfn, e_raw->lo, e_raw->hi);
806 		return;
807 	}
808 
809 	/*
810 	 * If the RMP entry for a particular PFN is not in an assigned state,
811 	 * then it is sometimes useful to get an idea of whether or not any RMP
812 	 * entries for other PFNs within the same 2MB region are assigned, since
813 	 * those too can affect the ability to access a particular PFN in
814 	 * certain situations, such as when the PFN is being accessed via a 2MB
815 	 * mapping in the host page table.
816 	 */
817 	pfn_i = ALIGN_DOWN(pfn, PTRS_PER_PMD);
818 	pfn_end = pfn_i + PTRS_PER_PMD;
819 
820 	pr_info("PFN 0x%llx unassigned, dumping non-zero entries in 2M PFN region: [0x%llx - 0x%llx]\n",
821 		pfn, pfn_i, pfn_end);
822 
823 	while (pfn_i < pfn_end) {
824 		e_raw = get_raw_rmpentry(pfn_i);
825 		if (IS_ERR(e_raw)) {
826 			pr_err("Error %ld reading RMP contents for PFN 0x%llx\n",
827 			       PTR_ERR(e_raw), pfn_i);
828 			pfn_i++;
829 			continue;
830 		}
831 
832 		if (e_raw->lo || e_raw->hi)
833 			pr_info("PFN: 0x%llx, [0x%016llx - 0x%016llx]\n", pfn_i, e_raw->lo, e_raw->hi);
834 		pfn_i++;
835 	}
836 }
837 
snp_dump_hva_rmpentry(unsigned long hva)838 void snp_dump_hva_rmpentry(unsigned long hva)
839 {
840 	unsigned long paddr;
841 	unsigned int level;
842 	pgd_t *pgd;
843 	pte_t *pte;
844 
845 	pgd = __va(read_cr3_pa());
846 	pgd += pgd_index(hva);
847 	pte = lookup_address_in_pgd(pgd, hva, &level);
848 
849 	if (!pte) {
850 		pr_err("Can't dump RMP entry for HVA %lx: no PTE/PFN found\n", hva);
851 		return;
852 	}
853 
854 	paddr = PFN_PHYS(pte_pfn(*pte)) | (hva & ~page_level_mask(level));
855 	dump_rmpentry(PHYS_PFN(paddr));
856 }
857 
858 /*
859  * PSMASH a 2MB aligned page into 4K pages in the RMP table while preserving the
860  * Validated bit.
861  */
psmash(u64 pfn)862 int psmash(u64 pfn)
863 {
864 	unsigned long paddr = pfn << PAGE_SHIFT;
865 	int ret;
866 
867 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
868 		return -ENODEV;
869 
870 	if (!pfn_valid(pfn))
871 		return -EINVAL;
872 
873 	/* Binutils version 2.36 supports the PSMASH mnemonic. */
874 	asm volatile(".byte 0xF3, 0x0F, 0x01, 0xFF"
875 		      : "=a" (ret)
876 		      : "a" (paddr)
877 		      : "memory", "cc");
878 
879 	return ret;
880 }
881 EXPORT_SYMBOL_GPL(psmash);
882 
883 /*
884  * If the kernel uses a 2MB or larger directmap mapping to write to an address,
885  * and that mapping contains any 4KB pages that are set to private in the RMP
886  * table, an RMP #PF will trigger and cause a host crash. Hypervisor code that
887  * owns the PFNs being transitioned will never attempt such a write, but other
888  * kernel tasks writing to other PFNs in the range may trigger these checks
889  * inadvertently due a large directmap mapping that happens to overlap such a
890  * PFN.
891  *
892  * Prevent this by splitting any 2MB+ mappings that might end up containing a
893  * mix of private/shared PFNs as a result of a subsequent RMPUPDATE for the
894  * PFN/rmp_level passed in.
895  *
896  * Note that there is no attempt here to scan all the RMP entries for the 2MB
897  * physical range, since it would only be worthwhile in determining if a
898  * subsequent RMPUPDATE for a 4KB PFN would result in all the entries being of
899  * the same shared/private state, thus avoiding the need to split the mapping.
900  * But that would mean the entries are currently in a mixed state, and so the
901  * mapping would have already been split as a result of prior transitions.
902  * And since the 4K split is only done if the mapping is 2MB+, and there isn't
903  * currently a mechanism in place to restore 2MB+ mappings, such a check would
904  * not provide any usable benefit.
905  *
906  * More specifics on how these checks are carried out can be found in APM
907  * Volume 2, "RMP and VMPL Access Checks".
908  */
adjust_direct_map(u64 pfn,int rmp_level)909 static int adjust_direct_map(u64 pfn, int rmp_level)
910 {
911 	unsigned long vaddr;
912 	unsigned int level;
913 	int npages, ret;
914 	pte_t *pte;
915 
916 	/*
917 	 * pfn_to_kaddr() will return a vaddr only within the direct
918 	 * map range.
919 	 */
920 	vaddr = (unsigned long)pfn_to_kaddr(pfn);
921 
922 	/* Only 4KB/2MB RMP entries are supported by current hardware. */
923 	if (WARN_ON_ONCE(rmp_level > PG_LEVEL_2M))
924 		return -EINVAL;
925 
926 	if (!pfn_valid(pfn))
927 		return -EINVAL;
928 
929 	if (rmp_level == PG_LEVEL_2M &&
930 	    (!IS_ALIGNED(pfn, PTRS_PER_PMD) || !pfn_valid(pfn + PTRS_PER_PMD - 1)))
931 		return -EINVAL;
932 
933 	/*
934 	 * If an entire 2MB physical range is being transitioned, then there is
935 	 * no risk of RMP #PFs due to write accesses from overlapping mappings,
936 	 * since even accesses from 1GB mappings will be treated as 2MB accesses
937 	 * as far as RMP table checks are concerned.
938 	 */
939 	if (rmp_level == PG_LEVEL_2M)
940 		return 0;
941 
942 	pte = lookup_address(vaddr, &level);
943 	if (!pte || pte_none(*pte))
944 		return 0;
945 
946 	if (level == PG_LEVEL_4K)
947 		return 0;
948 
949 	npages = page_level_size(rmp_level) / PAGE_SIZE;
950 	ret = set_memory_4k(vaddr, npages);
951 	if (ret)
952 		pr_warn("Failed to split direct map for PFN 0x%llx, ret: %d\n",
953 			pfn, ret);
954 
955 	return ret;
956 }
957 
958 /*
959  * It is expected that those operations are seldom enough so that no mutual
960  * exclusion of updaters is needed and thus the overlap error condition below
961  * should happen very rarely and would get resolved relatively quickly by
962  * the firmware.
963  *
964  * If not, one could consider introducing a mutex or so here to sync concurrent
965  * RMP updates and thus diminish the amount of cases where firmware needs to
966  * lock 2M ranges to protect against concurrent updates.
967  *
968  * The optimal solution would be range locking to avoid locking disjoint
969  * regions unnecessarily but there's no support for that yet.
970  */
rmpupdate(u64 pfn,struct rmp_state * state)971 static int rmpupdate(u64 pfn, struct rmp_state *state)
972 {
973 	unsigned long paddr = pfn << PAGE_SHIFT;
974 	int ret, level;
975 
976 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
977 		return -ENODEV;
978 
979 	level = RMP_TO_PG_LEVEL(state->pagesize);
980 
981 	if (adjust_direct_map(pfn, level))
982 		return -EFAULT;
983 
984 	do {
985 		/* Binutils version 2.36 supports the RMPUPDATE mnemonic. */
986 		asm volatile(".byte 0xF2, 0x0F, 0x01, 0xFE"
987 			     : "=a" (ret)
988 			     : "a" (paddr), "c" ((unsigned long)state)
989 			     : "memory", "cc");
990 	} while (ret == RMPUPDATE_FAIL_OVERLAP);
991 
992 	if (ret) {
993 		pr_err("RMPUPDATE failed for PFN %llx, pg_level: %d, ret: %d\n",
994 		       pfn, level, ret);
995 		dump_rmpentry(pfn);
996 		dump_stack();
997 		return -EFAULT;
998 	}
999 
1000 	return 0;
1001 }
1002 
1003 /* Transition a page to guest-owned/private state in the RMP table. */
rmp_make_private(u64 pfn,u64 gpa,enum pg_level level,u32 asid,bool immutable)1004 int rmp_make_private(u64 pfn, u64 gpa, enum pg_level level, u32 asid, bool immutable)
1005 {
1006 	struct rmp_state state;
1007 
1008 	memset(&state, 0, sizeof(state));
1009 	state.assigned = 1;
1010 	state.asid = asid;
1011 	state.immutable = immutable;
1012 	state.gpa = gpa;
1013 	state.pagesize = PG_LEVEL_TO_RMP(level);
1014 
1015 	return rmpupdate(pfn, &state);
1016 }
1017 EXPORT_SYMBOL_GPL(rmp_make_private);
1018 
1019 /* Transition a page to hypervisor-owned/shared state in the RMP table. */
rmp_make_shared(u64 pfn,enum pg_level level)1020 int rmp_make_shared(u64 pfn, enum pg_level level)
1021 {
1022 	struct rmp_state state;
1023 
1024 	memset(&state, 0, sizeof(state));
1025 	state.pagesize = PG_LEVEL_TO_RMP(level);
1026 
1027 	return rmpupdate(pfn, &state);
1028 }
1029 EXPORT_SYMBOL_GPL(rmp_make_shared);
1030 
snp_leak_pages(u64 pfn,unsigned int npages)1031 void snp_leak_pages(u64 pfn, unsigned int npages)
1032 {
1033 	struct page *page = pfn_to_page(pfn);
1034 
1035 	pr_warn("Leaking PFN range 0x%llx-0x%llx\n", pfn, pfn + npages);
1036 
1037 	spin_lock(&snp_leaked_pages_list_lock);
1038 	while (npages--) {
1039 
1040 		/*
1041 		 * Reuse the page's buddy list for chaining into the leaked
1042 		 * pages list. This page should not be on a free list currently
1043 		 * and is also unsafe to be added to a free list.
1044 		 */
1045 		if (likely(!PageCompound(page)) ||
1046 
1047 			/*
1048 			 * Skip inserting tail pages of compound page as
1049 			 * page->buddy_list of tail pages is not usable.
1050 			 */
1051 		    (PageHead(page) && compound_nr(page) <= npages))
1052 			list_add_tail(&page->buddy_list, &snp_leaked_pages_list);
1053 
1054 		dump_rmpentry(pfn);
1055 		snp_nr_leaked_pages++;
1056 		pfn++;
1057 		page++;
1058 	}
1059 	spin_unlock(&snp_leaked_pages_list_lock);
1060 }
1061 EXPORT_SYMBOL_GPL(snp_leak_pages);
1062 
kdump_sev_callback(void)1063 void kdump_sev_callback(void)
1064 {
1065 	/*
1066 	 * Do wbinvd() on remote CPUs when SNP is enabled in order to
1067 	 * safely do SNP_SHUTDOWN on the local CPU.
1068 	 */
1069 	if (cc_platform_has(CC_ATTR_HOST_SEV_SNP))
1070 		wbinvd();
1071 }
1072