xref: /openbmc/linux/arch/x86/mm/mem_encrypt_amd.c (revision 65b96377)
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/cc_platform.h>
24 
25 #include <asm/tlbflush.h>
26 #include <asm/fixmap.h>
27 #include <asm/setup.h>
28 #include <asm/bootparam.h>
29 #include <asm/set_memory.h>
30 #include <asm/cacheflush.h>
31 #include <asm/processor-flags.h>
32 #include <asm/msr.h>
33 #include <asm/cmdline.h>
34 
35 #include "mm_internal.h"
36 
37 /*
38  * Since SME related variables are set early in the boot process they must
39  * reside in the .data section so as not to be zeroed out when the .bss
40  * section is later cleared.
41  */
42 u64 sme_me_mask __section(".data") = 0;
43 u64 sev_status __section(".data") = 0;
44 u64 sev_check_data __section(".data") = 0;
45 EXPORT_SYMBOL(sme_me_mask);
46 
47 /* Buffer used for early in-place encryption by BSP, no locking needed */
48 static char sme_early_buffer[PAGE_SIZE] __initdata __aligned(PAGE_SIZE);
49 
50 /*
51  * This routine does not change the underlying encryption setting of the
52  * page(s) that map this memory. It assumes that eventually the memory is
53  * meant to be accessed as either encrypted or decrypted but the contents
54  * are currently not in the desired state.
55  *
56  * This routine follows the steps outlined in the AMD64 Architecture
57  * Programmer's Manual Volume 2, Section 7.10.8 Encrypt-in-Place.
58  */
59 static void __init __sme_early_enc_dec(resource_size_t paddr,
60 				       unsigned long size, bool enc)
61 {
62 	void *src, *dst;
63 	size_t len;
64 
65 	if (!sme_me_mask)
66 		return;
67 
68 	wbinvd();
69 
70 	/*
71 	 * There are limited number of early mapping slots, so map (at most)
72 	 * one page at time.
73 	 */
74 	while (size) {
75 		len = min_t(size_t, sizeof(sme_early_buffer), size);
76 
77 		/*
78 		 * Create mappings for the current and desired format of
79 		 * the memory. Use a write-protected mapping for the source.
80 		 */
81 		src = enc ? early_memremap_decrypted_wp(paddr, len) :
82 			    early_memremap_encrypted_wp(paddr, len);
83 
84 		dst = enc ? early_memremap_encrypted(paddr, len) :
85 			    early_memremap_decrypted(paddr, len);
86 
87 		/*
88 		 * If a mapping can't be obtained to perform the operation,
89 		 * then eventual access of that area in the desired mode
90 		 * will cause a crash.
91 		 */
92 		BUG_ON(!src || !dst);
93 
94 		/*
95 		 * Use a temporary buffer, of cache-line multiple size, to
96 		 * avoid data corruption as documented in the APM.
97 		 */
98 		memcpy(sme_early_buffer, src, len);
99 		memcpy(dst, sme_early_buffer, len);
100 
101 		early_memunmap(dst, len);
102 		early_memunmap(src, len);
103 
104 		paddr += len;
105 		size -= len;
106 	}
107 }
108 
109 void __init sme_early_encrypt(resource_size_t paddr, unsigned long size)
110 {
111 	__sme_early_enc_dec(paddr, size, true);
112 }
113 
114 void __init sme_early_decrypt(resource_size_t paddr, unsigned long size)
115 {
116 	__sme_early_enc_dec(paddr, size, false);
117 }
118 
119 static void __init __sme_early_map_unmap_mem(void *vaddr, unsigned long size,
120 					     bool map)
121 {
122 	unsigned long paddr = (unsigned long)vaddr - __PAGE_OFFSET;
123 	pmdval_t pmd_flags, pmd;
124 
125 	/* Use early_pmd_flags but remove the encryption mask */
126 	pmd_flags = __sme_clr(early_pmd_flags);
127 
128 	do {
129 		pmd = map ? (paddr & PMD_MASK) + pmd_flags : 0;
130 		__early_make_pgtable((unsigned long)vaddr, pmd);
131 
132 		vaddr += PMD_SIZE;
133 		paddr += PMD_SIZE;
134 		size = (size <= PMD_SIZE) ? 0 : size - PMD_SIZE;
135 	} while (size);
136 
137 	flush_tlb_local();
138 }
139 
140 void __init sme_unmap_bootdata(char *real_mode_data)
141 {
142 	struct boot_params *boot_data;
143 	unsigned long cmdline_paddr;
144 
145 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
146 		return;
147 
148 	/* Get the command line address before unmapping the real_mode_data */
149 	boot_data = (struct boot_params *)real_mode_data;
150 	cmdline_paddr = boot_data->hdr.cmd_line_ptr | ((u64)boot_data->ext_cmd_line_ptr << 32);
151 
152 	__sme_early_map_unmap_mem(real_mode_data, sizeof(boot_params), false);
153 
154 	if (!cmdline_paddr)
155 		return;
156 
157 	__sme_early_map_unmap_mem(__va(cmdline_paddr), COMMAND_LINE_SIZE, false);
158 }
159 
160 void __init sme_map_bootdata(char *real_mode_data)
161 {
162 	struct boot_params *boot_data;
163 	unsigned long cmdline_paddr;
164 
165 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
166 		return;
167 
168 	__sme_early_map_unmap_mem(real_mode_data, sizeof(boot_params), true);
169 
170 	/* Get the command line address after mapping the real_mode_data */
171 	boot_data = (struct boot_params *)real_mode_data;
172 	cmdline_paddr = boot_data->hdr.cmd_line_ptr | ((u64)boot_data->ext_cmd_line_ptr << 32);
173 
174 	if (!cmdline_paddr)
175 		return;
176 
177 	__sme_early_map_unmap_mem(__va(cmdline_paddr), COMMAND_LINE_SIZE, true);
178 }
179 
180 void __init sev_setup_arch(void)
181 {
182 	phys_addr_t total_mem = memblock_phys_mem_size();
183 	unsigned long size;
184 
185 	if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
186 		return;
187 
188 	/*
189 	 * For SEV, all DMA has to occur via shared/unencrypted pages.
190 	 * SEV uses SWIOTLB to make this happen without changing device
191 	 * drivers. However, depending on the workload being run, the
192 	 * default 64MB of SWIOTLB may not be enough and SWIOTLB may
193 	 * run out of buffers for DMA, resulting in I/O errors and/or
194 	 * performance degradation especially with high I/O workloads.
195 	 *
196 	 * Adjust the default size of SWIOTLB for SEV guests using
197 	 * a percentage of guest memory for SWIOTLB buffers.
198 	 * Also, as the SWIOTLB bounce buffer memory is allocated
199 	 * from low memory, ensure that the adjusted size is within
200 	 * the limits of low available memory.
201 	 *
202 	 * The percentage of guest memory used here for SWIOTLB buffers
203 	 * is more of an approximation of the static adjustment which
204 	 * 64MB for <1G, and ~128M to 256M for 1G-to-4G, i.e., the 6%
205 	 */
206 	size = total_mem * 6 / 100;
207 	size = clamp_val(size, IO_TLB_DEFAULT_SIZE, SZ_1G);
208 	swiotlb_adjust_size(size);
209 }
210 
211 static unsigned long pg_level_to_pfn(int level, pte_t *kpte, pgprot_t *ret_prot)
212 {
213 	unsigned long pfn = 0;
214 	pgprot_t prot;
215 
216 	switch (level) {
217 	case PG_LEVEL_4K:
218 		pfn = pte_pfn(*kpte);
219 		prot = pte_pgprot(*kpte);
220 		break;
221 	case PG_LEVEL_2M:
222 		pfn = pmd_pfn(*(pmd_t *)kpte);
223 		prot = pmd_pgprot(*(pmd_t *)kpte);
224 		break;
225 	case PG_LEVEL_1G:
226 		pfn = pud_pfn(*(pud_t *)kpte);
227 		prot = pud_pgprot(*(pud_t *)kpte);
228 		break;
229 	default:
230 		WARN_ONCE(1, "Invalid level for kpte\n");
231 		return 0;
232 	}
233 
234 	if (ret_prot)
235 		*ret_prot = prot;
236 
237 	return pfn;
238 }
239 
240 static bool amd_enc_tlb_flush_required(bool enc)
241 {
242 	return true;
243 }
244 
245 static bool amd_enc_cache_flush_required(void)
246 {
247 	return !cpu_feature_enabled(X86_FEATURE_SME_COHERENT);
248 }
249 
250 static void enc_dec_hypercall(unsigned long vaddr, int npages, bool enc)
251 {
252 #ifdef CONFIG_PARAVIRT
253 	unsigned long sz = npages << PAGE_SHIFT;
254 	unsigned long vaddr_end = vaddr + sz;
255 
256 	while (vaddr < vaddr_end) {
257 		int psize, pmask, level;
258 		unsigned long pfn;
259 		pte_t *kpte;
260 
261 		kpte = lookup_address(vaddr, &level);
262 		if (!kpte || pte_none(*kpte)) {
263 			WARN_ONCE(1, "kpte lookup for vaddr\n");
264 			return;
265 		}
266 
267 		pfn = pg_level_to_pfn(level, kpte, NULL);
268 		if (!pfn)
269 			continue;
270 
271 		psize = page_level_size(level);
272 		pmask = page_level_mask(level);
273 
274 		notify_page_enc_status_changed(pfn, psize >> PAGE_SHIFT, enc);
275 
276 		vaddr = (vaddr & pmask) + psize;
277 	}
278 #endif
279 }
280 
281 static void amd_enc_status_change_prepare(unsigned long vaddr, int npages, bool enc)
282 {
283 }
284 
285 /* Return true unconditionally: return value doesn't matter for the SEV side */
286 static bool amd_enc_status_change_finish(unsigned long vaddr, int npages, bool enc)
287 {
288 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
289 		enc_dec_hypercall(vaddr, npages, enc);
290 
291 	return true;
292 }
293 
294 static void __init __set_clr_pte_enc(pte_t *kpte, int level, bool enc)
295 {
296 	pgprot_t old_prot, new_prot;
297 	unsigned long pfn, pa, size;
298 	pte_t new_pte;
299 
300 	pfn = pg_level_to_pfn(level, kpte, &old_prot);
301 	if (!pfn)
302 		return;
303 
304 	new_prot = old_prot;
305 	if (enc)
306 		pgprot_val(new_prot) |= _PAGE_ENC;
307 	else
308 		pgprot_val(new_prot) &= ~_PAGE_ENC;
309 
310 	/* If prot is same then do nothing. */
311 	if (pgprot_val(old_prot) == pgprot_val(new_prot))
312 		return;
313 
314 	pa = pfn << PAGE_SHIFT;
315 	size = page_level_size(level);
316 
317 	/*
318 	 * We are going to perform in-place en-/decryption and change the
319 	 * physical page attribute from C=1 to C=0 or vice versa. Flush the
320 	 * caches to ensure that data gets accessed with the correct C-bit.
321 	 */
322 	clflush_cache_range(__va(pa), size);
323 
324 	/* Encrypt/decrypt the contents in-place */
325 	if (enc)
326 		sme_early_encrypt(pa, size);
327 	else
328 		sme_early_decrypt(pa, size);
329 
330 	/* Change the page encryption mask. */
331 	new_pte = pfn_pte(pfn, new_prot);
332 	set_pte_atomic(kpte, new_pte);
333 }
334 
335 static int __init early_set_memory_enc_dec(unsigned long vaddr,
336 					   unsigned long size, bool enc)
337 {
338 	unsigned long vaddr_end, vaddr_next, start;
339 	unsigned long psize, pmask;
340 	int split_page_size_mask;
341 	int level, ret;
342 	pte_t *kpte;
343 
344 	start = vaddr;
345 	vaddr_next = vaddr;
346 	vaddr_end = vaddr + size;
347 
348 	for (; vaddr < vaddr_end; vaddr = vaddr_next) {
349 		kpte = lookup_address(vaddr, &level);
350 		if (!kpte || pte_none(*kpte)) {
351 			ret = 1;
352 			goto out;
353 		}
354 
355 		if (level == PG_LEVEL_4K) {
356 			__set_clr_pte_enc(kpte, level, enc);
357 			vaddr_next = (vaddr & PAGE_MASK) + PAGE_SIZE;
358 			continue;
359 		}
360 
361 		psize = page_level_size(level);
362 		pmask = page_level_mask(level);
363 
364 		/*
365 		 * Check whether we can change the large page in one go.
366 		 * We request a split when the address is not aligned and
367 		 * the number of pages to set/clear encryption bit is smaller
368 		 * than the number of pages in the large page.
369 		 */
370 		if (vaddr == (vaddr & pmask) &&
371 		    ((vaddr_end - vaddr) >= psize)) {
372 			__set_clr_pte_enc(kpte, level, enc);
373 			vaddr_next = (vaddr & pmask) + psize;
374 			continue;
375 		}
376 
377 		/*
378 		 * The virtual address is part of a larger page, create the next
379 		 * level page table mapping (4K or 2M). If it is part of a 2M
380 		 * page then we request a split of the large page into 4K
381 		 * chunks. A 1GB large page is split into 2M pages, resp.
382 		 */
383 		if (level == PG_LEVEL_2M)
384 			split_page_size_mask = 0;
385 		else
386 			split_page_size_mask = 1 << PG_LEVEL_2M;
387 
388 		/*
389 		 * kernel_physical_mapping_change() does not flush the TLBs, so
390 		 * a TLB flush is required after we exit from the for loop.
391 		 */
392 		kernel_physical_mapping_change(__pa(vaddr & pmask),
393 					       __pa((vaddr_end & pmask) + psize),
394 					       split_page_size_mask);
395 	}
396 
397 	ret = 0;
398 
399 	early_set_mem_enc_dec_hypercall(start, PAGE_ALIGN(size) >> PAGE_SHIFT, enc);
400 out:
401 	__flush_tlb_all();
402 	return ret;
403 }
404 
405 int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size)
406 {
407 	return early_set_memory_enc_dec(vaddr, size, false);
408 }
409 
410 int __init early_set_memory_encrypted(unsigned long vaddr, unsigned long size)
411 {
412 	return early_set_memory_enc_dec(vaddr, size, true);
413 }
414 
415 void __init early_set_mem_enc_dec_hypercall(unsigned long vaddr, int npages, bool enc)
416 {
417 	enc_dec_hypercall(vaddr, npages, enc);
418 }
419 
420 void __init sme_early_init(void)
421 {
422 	unsigned int i;
423 
424 	if (!sme_me_mask)
425 		return;
426 
427 	early_pmd_flags = __sme_set(early_pmd_flags);
428 
429 	__supported_pte_mask = __sme_set(__supported_pte_mask);
430 
431 	/* Update the protection map with memory encryption mask */
432 	for (i = 0; i < ARRAY_SIZE(protection_map); i++)
433 		protection_map[i] = pgprot_encrypted(protection_map[i]);
434 
435 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
436 		swiotlb_force = SWIOTLB_FORCE;
437 
438 	x86_platform.guest.enc_status_change_prepare = amd_enc_status_change_prepare;
439 	x86_platform.guest.enc_status_change_finish  = amd_enc_status_change_finish;
440 	x86_platform.guest.enc_tlb_flush_required    = amd_enc_tlb_flush_required;
441 	x86_platform.guest.enc_cache_flush_required  = amd_enc_cache_flush_required;
442 }
443 
444 void __init mem_encrypt_free_decrypted_mem(void)
445 {
446 	unsigned long vaddr, vaddr_end, npages;
447 	int r;
448 
449 	vaddr = (unsigned long)__start_bss_decrypted_unused;
450 	vaddr_end = (unsigned long)__end_bss_decrypted;
451 	npages = (vaddr_end - vaddr) >> PAGE_SHIFT;
452 
453 	/*
454 	 * The unused memory range was mapped decrypted, change the encryption
455 	 * attribute from decrypted to encrypted before freeing it.
456 	 */
457 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
458 		r = set_memory_encrypted(vaddr, npages);
459 		if (r) {
460 			pr_warn("failed to free unused decrypted pages\n");
461 			return;
462 		}
463 	}
464 
465 	free_init_pages("unused decrypted", vaddr, vaddr_end);
466 }
467