xref: /openbmc/linux/arch/x86/mm/mem_encrypt_amd.c (revision 54d8c1d3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AMD Memory Encryption Support
4  *
5  * Copyright (C) 2016 Advanced Micro Devices, Inc.
6  *
7  * Author: Tom Lendacky <thomas.lendacky@amd.com>
8  */
9 
10 #define DISABLE_BRANCH_PROFILING
11 
12 #include <linux/linkage.h>
13 #include <linux/init.h>
14 #include <linux/mm.h>
15 #include <linux/dma-direct.h>
16 #include <linux/swiotlb.h>
17 #include <linux/mem_encrypt.h>
18 #include <linux/device.h>
19 #include <linux/kernel.h>
20 #include <linux/bitops.h>
21 #include <linux/dma-mapping.h>
22 #include <linux/virtio_config.h>
23 #include <linux/virtio_anchor.h>
24 #include <linux/cc_platform.h>
25 
26 #include <asm/tlbflush.h>
27 #include <asm/fixmap.h>
28 #include <asm/setup.h>
29 #include <asm/mem_encrypt.h>
30 #include <asm/bootparam.h>
31 #include <asm/set_memory.h>
32 #include <asm/cacheflush.h>
33 #include <asm/processor-flags.h>
34 #include <asm/msr.h>
35 #include <asm/cmdline.h>
36 #include <asm/sev.h>
37 #include <asm/ia32.h>
38 
39 #include "mm_internal.h"
40 
41 /*
42  * Since SME related variables are set early in the boot process they must
43  * reside in the .data section so as not to be zeroed out when the .bss
44  * section is later cleared.
45  */
46 u64 sme_me_mask __section(".data") = 0;
47 u64 sev_status __section(".data") = 0;
48 u64 sev_check_data __section(".data") = 0;
49 EXPORT_SYMBOL(sme_me_mask);
50 
51 /* Buffer used for early in-place encryption by BSP, no locking needed */
52 static char sme_early_buffer[PAGE_SIZE] __initdata __aligned(PAGE_SIZE);
53 
54 /*
55  * SNP-specific routine which needs to additionally change the page state from
56  * private to shared before copying the data from the source to destination and
57  * restore after the copy.
58  */
59 static inline void __init snp_memcpy(void *dst, void *src, size_t sz,
60 				     unsigned long paddr, bool decrypt)
61 {
62 	unsigned long npages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
63 
64 	if (decrypt) {
65 		/*
66 		 * @paddr needs to be accessed decrypted, mark the page shared in
67 		 * the RMP table before copying it.
68 		 */
69 		early_snp_set_memory_shared((unsigned long)__va(paddr), paddr, npages);
70 
71 		memcpy(dst, src, sz);
72 
73 		/* Restore the page state after the memcpy. */
74 		early_snp_set_memory_private((unsigned long)__va(paddr), paddr, npages);
75 	} else {
76 		/*
77 		 * @paddr need to be accessed encrypted, no need for the page state
78 		 * change.
79 		 */
80 		memcpy(dst, src, sz);
81 	}
82 }
83 
84 /*
85  * This routine does not change the underlying encryption setting of the
86  * page(s) that map this memory. It assumes that eventually the memory is
87  * meant to be accessed as either encrypted or decrypted but the contents
88  * are currently not in the desired state.
89  *
90  * This routine follows the steps outlined in the AMD64 Architecture
91  * Programmer's Manual Volume 2, Section 7.10.8 Encrypt-in-Place.
92  */
93 static void __init __sme_early_enc_dec(resource_size_t paddr,
94 				       unsigned long size, bool enc)
95 {
96 	void *src, *dst;
97 	size_t len;
98 
99 	if (!sme_me_mask)
100 		return;
101 
102 	wbinvd();
103 
104 	/*
105 	 * There are limited number of early mapping slots, so map (at most)
106 	 * one page at time.
107 	 */
108 	while (size) {
109 		len = min_t(size_t, sizeof(sme_early_buffer), size);
110 
111 		/*
112 		 * Create mappings for the current and desired format of
113 		 * the memory. Use a write-protected mapping for the source.
114 		 */
115 		src = enc ? early_memremap_decrypted_wp(paddr, len) :
116 			    early_memremap_encrypted_wp(paddr, len);
117 
118 		dst = enc ? early_memremap_encrypted(paddr, len) :
119 			    early_memremap_decrypted(paddr, len);
120 
121 		/*
122 		 * If a mapping can't be obtained to perform the operation,
123 		 * then eventual access of that area in the desired mode
124 		 * will cause a crash.
125 		 */
126 		BUG_ON(!src || !dst);
127 
128 		/*
129 		 * Use a temporary buffer, of cache-line multiple size, to
130 		 * avoid data corruption as documented in the APM.
131 		 */
132 		if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) {
133 			snp_memcpy(sme_early_buffer, src, len, paddr, enc);
134 			snp_memcpy(dst, sme_early_buffer, len, paddr, !enc);
135 		} else {
136 			memcpy(sme_early_buffer, src, len);
137 			memcpy(dst, sme_early_buffer, len);
138 		}
139 
140 		early_memunmap(dst, len);
141 		early_memunmap(src, len);
142 
143 		paddr += len;
144 		size -= len;
145 	}
146 }
147 
148 void __init sme_early_encrypt(resource_size_t paddr, unsigned long size)
149 {
150 	__sme_early_enc_dec(paddr, size, true);
151 }
152 
153 void __init sme_early_decrypt(resource_size_t paddr, unsigned long size)
154 {
155 	__sme_early_enc_dec(paddr, size, false);
156 }
157 
158 static void __init __sme_early_map_unmap_mem(void *vaddr, unsigned long size,
159 					     bool map)
160 {
161 	unsigned long paddr = (unsigned long)vaddr - __PAGE_OFFSET;
162 	pmdval_t pmd_flags, pmd;
163 
164 	/* Use early_pmd_flags but remove the encryption mask */
165 	pmd_flags = __sme_clr(early_pmd_flags);
166 
167 	do {
168 		pmd = map ? (paddr & PMD_MASK) + pmd_flags : 0;
169 		__early_make_pgtable((unsigned long)vaddr, pmd);
170 
171 		vaddr += PMD_SIZE;
172 		paddr += PMD_SIZE;
173 		size = (size <= PMD_SIZE) ? 0 : size - PMD_SIZE;
174 	} while (size);
175 
176 	flush_tlb_local();
177 }
178 
179 void __init sme_unmap_bootdata(char *real_mode_data)
180 {
181 	struct boot_params *boot_data;
182 	unsigned long cmdline_paddr;
183 
184 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
185 		return;
186 
187 	/* Get the command line address before unmapping the real_mode_data */
188 	boot_data = (struct boot_params *)real_mode_data;
189 	cmdline_paddr = boot_data->hdr.cmd_line_ptr | ((u64)boot_data->ext_cmd_line_ptr << 32);
190 
191 	__sme_early_map_unmap_mem(real_mode_data, sizeof(boot_params), false);
192 
193 	if (!cmdline_paddr)
194 		return;
195 
196 	__sme_early_map_unmap_mem(__va(cmdline_paddr), COMMAND_LINE_SIZE, false);
197 }
198 
199 void __init sme_map_bootdata(char *real_mode_data)
200 {
201 	struct boot_params *boot_data;
202 	unsigned long cmdline_paddr;
203 
204 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
205 		return;
206 
207 	__sme_early_map_unmap_mem(real_mode_data, sizeof(boot_params), true);
208 
209 	/* Get the command line address after mapping the real_mode_data */
210 	boot_data = (struct boot_params *)real_mode_data;
211 	cmdline_paddr = boot_data->hdr.cmd_line_ptr | ((u64)boot_data->ext_cmd_line_ptr << 32);
212 
213 	if (!cmdline_paddr)
214 		return;
215 
216 	__sme_early_map_unmap_mem(__va(cmdline_paddr), COMMAND_LINE_SIZE, true);
217 }
218 
219 void __init sev_setup_arch(void)
220 {
221 	phys_addr_t total_mem = memblock_phys_mem_size();
222 	unsigned long size;
223 
224 	if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
225 		return;
226 
227 	/*
228 	 * For SEV, all DMA has to occur via shared/unencrypted pages.
229 	 * SEV uses SWIOTLB to make this happen without changing device
230 	 * drivers. However, depending on the workload being run, the
231 	 * default 64MB of SWIOTLB may not be enough and SWIOTLB may
232 	 * run out of buffers for DMA, resulting in I/O errors and/or
233 	 * performance degradation especially with high I/O workloads.
234 	 *
235 	 * Adjust the default size of SWIOTLB for SEV guests using
236 	 * a percentage of guest memory for SWIOTLB buffers.
237 	 * Also, as the SWIOTLB bounce buffer memory is allocated
238 	 * from low memory, ensure that the adjusted size is within
239 	 * the limits of low available memory.
240 	 *
241 	 * The percentage of guest memory used here for SWIOTLB buffers
242 	 * is more of an approximation of the static adjustment which
243 	 * 64MB for <1G, and ~128M to 256M for 1G-to-4G, i.e., the 6%
244 	 */
245 	size = total_mem * 6 / 100;
246 	size = clamp_val(size, IO_TLB_DEFAULT_SIZE, SZ_1G);
247 	swiotlb_adjust_size(size);
248 
249 	/* Set restricted memory access for virtio. */
250 	virtio_set_mem_acc_cb(virtio_require_restricted_mem_acc);
251 }
252 
253 static unsigned long pg_level_to_pfn(int level, pte_t *kpte, pgprot_t *ret_prot)
254 {
255 	unsigned long pfn = 0;
256 	pgprot_t prot;
257 
258 	switch (level) {
259 	case PG_LEVEL_4K:
260 		pfn = pte_pfn(*kpte);
261 		prot = pte_pgprot(*kpte);
262 		break;
263 	case PG_LEVEL_2M:
264 		pfn = pmd_pfn(*(pmd_t *)kpte);
265 		prot = pmd_pgprot(*(pmd_t *)kpte);
266 		break;
267 	case PG_LEVEL_1G:
268 		pfn = pud_pfn(*(pud_t *)kpte);
269 		prot = pud_pgprot(*(pud_t *)kpte);
270 		break;
271 	default:
272 		WARN_ONCE(1, "Invalid level for kpte\n");
273 		return 0;
274 	}
275 
276 	if (ret_prot)
277 		*ret_prot = prot;
278 
279 	return pfn;
280 }
281 
282 static bool amd_enc_tlb_flush_required(bool enc)
283 {
284 	return true;
285 }
286 
287 static bool amd_enc_cache_flush_required(void)
288 {
289 	return !cpu_feature_enabled(X86_FEATURE_SME_COHERENT);
290 }
291 
292 static void enc_dec_hypercall(unsigned long vaddr, unsigned long size, bool enc)
293 {
294 #ifdef CONFIG_PARAVIRT
295 	unsigned long vaddr_end = vaddr + size;
296 
297 	while (vaddr < vaddr_end) {
298 		int psize, pmask, level;
299 		unsigned long pfn;
300 		pte_t *kpte;
301 
302 		kpte = lookup_address(vaddr, &level);
303 		if (!kpte || pte_none(*kpte)) {
304 			WARN_ONCE(1, "kpte lookup for vaddr\n");
305 			return;
306 		}
307 
308 		pfn = pg_level_to_pfn(level, kpte, NULL);
309 		if (!pfn)
310 			continue;
311 
312 		psize = page_level_size(level);
313 		pmask = page_level_mask(level);
314 
315 		notify_page_enc_status_changed(pfn, psize >> PAGE_SHIFT, enc);
316 
317 		vaddr = (vaddr & pmask) + psize;
318 	}
319 #endif
320 }
321 
322 static bool amd_enc_status_change_prepare(unsigned long vaddr, int npages, bool enc)
323 {
324 	/*
325 	 * To maintain the security guarantees of SEV-SNP guests, make sure
326 	 * to invalidate the memory before encryption attribute is cleared.
327 	 */
328 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP) && !enc)
329 		snp_set_memory_shared(vaddr, npages);
330 
331 	return true;
332 }
333 
334 /* Return true unconditionally: return value doesn't matter for the SEV side */
335 static bool amd_enc_status_change_finish(unsigned long vaddr, int npages, bool enc)
336 {
337 	/*
338 	 * After memory is mapped encrypted in the page table, validate it
339 	 * so that it is consistent with the page table updates.
340 	 */
341 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP) && enc)
342 		snp_set_memory_private(vaddr, npages);
343 
344 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
345 		enc_dec_hypercall(vaddr, npages << PAGE_SHIFT, enc);
346 
347 	return true;
348 }
349 
350 static void __init __set_clr_pte_enc(pte_t *kpte, int level, bool enc)
351 {
352 	pgprot_t old_prot, new_prot;
353 	unsigned long pfn, pa, size;
354 	pte_t new_pte;
355 
356 	pfn = pg_level_to_pfn(level, kpte, &old_prot);
357 	if (!pfn)
358 		return;
359 
360 	new_prot = old_prot;
361 	if (enc)
362 		pgprot_val(new_prot) |= _PAGE_ENC;
363 	else
364 		pgprot_val(new_prot) &= ~_PAGE_ENC;
365 
366 	/* If prot is same then do nothing. */
367 	if (pgprot_val(old_prot) == pgprot_val(new_prot))
368 		return;
369 
370 	pa = pfn << PAGE_SHIFT;
371 	size = page_level_size(level);
372 
373 	/*
374 	 * We are going to perform in-place en-/decryption and change the
375 	 * physical page attribute from C=1 to C=0 or vice versa. Flush the
376 	 * caches to ensure that data gets accessed with the correct C-bit.
377 	 */
378 	clflush_cache_range(__va(pa), size);
379 
380 	/* Encrypt/decrypt the contents in-place */
381 	if (enc) {
382 		sme_early_encrypt(pa, size);
383 	} else {
384 		sme_early_decrypt(pa, size);
385 
386 		/*
387 		 * ON SNP, the page state in the RMP table must happen
388 		 * before the page table updates.
389 		 */
390 		early_snp_set_memory_shared((unsigned long)__va(pa), pa, 1);
391 	}
392 
393 	/* Change the page encryption mask. */
394 	new_pte = pfn_pte(pfn, new_prot);
395 	set_pte_atomic(kpte, new_pte);
396 
397 	/*
398 	 * If page is set encrypted in the page table, then update the RMP table to
399 	 * add this page as private.
400 	 */
401 	if (enc)
402 		early_snp_set_memory_private((unsigned long)__va(pa), pa, 1);
403 }
404 
405 static int __init early_set_memory_enc_dec(unsigned long vaddr,
406 					   unsigned long size, bool enc)
407 {
408 	unsigned long vaddr_end, vaddr_next, start;
409 	unsigned long psize, pmask;
410 	int split_page_size_mask;
411 	int level, ret;
412 	pte_t *kpte;
413 
414 	start = vaddr;
415 	vaddr_next = vaddr;
416 	vaddr_end = vaddr + size;
417 
418 	for (; vaddr < vaddr_end; vaddr = vaddr_next) {
419 		kpte = lookup_address(vaddr, &level);
420 		if (!kpte || pte_none(*kpte)) {
421 			ret = 1;
422 			goto out;
423 		}
424 
425 		if (level == PG_LEVEL_4K) {
426 			__set_clr_pte_enc(kpte, level, enc);
427 			vaddr_next = (vaddr & PAGE_MASK) + PAGE_SIZE;
428 			continue;
429 		}
430 
431 		psize = page_level_size(level);
432 		pmask = page_level_mask(level);
433 
434 		/*
435 		 * Check whether we can change the large page in one go.
436 		 * We request a split when the address is not aligned and
437 		 * the number of pages to set/clear encryption bit is smaller
438 		 * than the number of pages in the large page.
439 		 */
440 		if (vaddr == (vaddr & pmask) &&
441 		    ((vaddr_end - vaddr) >= psize)) {
442 			__set_clr_pte_enc(kpte, level, enc);
443 			vaddr_next = (vaddr & pmask) + psize;
444 			continue;
445 		}
446 
447 		/*
448 		 * The virtual address is part of a larger page, create the next
449 		 * level page table mapping (4K or 2M). If it is part of a 2M
450 		 * page then we request a split of the large page into 4K
451 		 * chunks. A 1GB large page is split into 2M pages, resp.
452 		 */
453 		if (level == PG_LEVEL_2M)
454 			split_page_size_mask = 0;
455 		else
456 			split_page_size_mask = 1 << PG_LEVEL_2M;
457 
458 		/*
459 		 * kernel_physical_mapping_change() does not flush the TLBs, so
460 		 * a TLB flush is required after we exit from the for loop.
461 		 */
462 		kernel_physical_mapping_change(__pa(vaddr & pmask),
463 					       __pa((vaddr_end & pmask) + psize),
464 					       split_page_size_mask);
465 	}
466 
467 	ret = 0;
468 
469 	early_set_mem_enc_dec_hypercall(start, size, enc);
470 out:
471 	__flush_tlb_all();
472 	return ret;
473 }
474 
475 int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size)
476 {
477 	return early_set_memory_enc_dec(vaddr, size, false);
478 }
479 
480 int __init early_set_memory_encrypted(unsigned long vaddr, unsigned long size)
481 {
482 	return early_set_memory_enc_dec(vaddr, size, true);
483 }
484 
485 void __init early_set_mem_enc_dec_hypercall(unsigned long vaddr, unsigned long size, bool enc)
486 {
487 	enc_dec_hypercall(vaddr, size, enc);
488 }
489 
490 void __init sme_early_init(void)
491 {
492 	if (!sme_me_mask)
493 		return;
494 
495 	early_pmd_flags = __sme_set(early_pmd_flags);
496 
497 	__supported_pte_mask = __sme_set(__supported_pte_mask);
498 
499 	/* Update the protection map with memory encryption mask */
500 	add_encrypt_protection_map();
501 
502 	x86_platform.guest.enc_status_change_prepare = amd_enc_status_change_prepare;
503 	x86_platform.guest.enc_status_change_finish  = amd_enc_status_change_finish;
504 	x86_platform.guest.enc_tlb_flush_required    = amd_enc_tlb_flush_required;
505 	x86_platform.guest.enc_cache_flush_required  = amd_enc_cache_flush_required;
506 
507 	/*
508 	 * AMD-SEV-ES intercepts the RDMSR to read the X2APIC ID in the
509 	 * parallel bringup low level code. That raises #VC which cannot be
510 	 * handled there.
511 	 * It does not provide a RDMSR GHCB protocol so the early startup
512 	 * code cannot directly communicate with the secure firmware. The
513 	 * alternative solution to retrieve the APIC ID via CPUID(0xb),
514 	 * which is covered by the GHCB protocol, is not viable either
515 	 * because there is no enforcement of the CPUID(0xb) provided
516 	 * "initial" APIC ID to be the same as the real APIC ID.
517 	 * Disable parallel bootup.
518 	 */
519 	if (sev_status & MSR_AMD64_SEV_ES_ENABLED)
520 		x86_cpuinit.parallel_bringup = false;
521 
522 	/*
523 	 * The VMM is capable of injecting interrupt 0x80 and triggering the
524 	 * compatibility syscall path.
525 	 *
526 	 * By default, the 32-bit emulation is disabled in order to ensure
527 	 * the safety of the VM.
528 	 */
529 	if (sev_status & MSR_AMD64_SEV_ENABLED)
530 		ia32_disable();
531 }
532 
533 void __init mem_encrypt_free_decrypted_mem(void)
534 {
535 	unsigned long vaddr, vaddr_end, npages;
536 	int r;
537 
538 	vaddr = (unsigned long)__start_bss_decrypted_unused;
539 	vaddr_end = (unsigned long)__end_bss_decrypted;
540 	npages = (vaddr_end - vaddr) >> PAGE_SHIFT;
541 
542 	/*
543 	 * If the unused memory range was mapped decrypted, change the encryption
544 	 * attribute from decrypted to encrypted before freeing it. Base the
545 	 * re-encryption on the same condition used for the decryption in
546 	 * sme_postprocess_startup(). Higher level abstractions, such as
547 	 * CC_ATTR_MEM_ENCRYPT, aren't necessarily equivalent in a Hyper-V VM
548 	 * using vTOM, where sme_me_mask is always zero.
549 	 */
550 	if (sme_me_mask) {
551 		r = set_memory_encrypted(vaddr, npages);
552 		if (r) {
553 			pr_warn("failed to free unused decrypted pages\n");
554 			return;
555 		}
556 	}
557 
558 	free_init_pages("unused decrypted", vaddr, vaddr_end);
559 }
560