xref: /openbmc/linux/arch/x86/mm/mem_encrypt_amd.c (revision 94d964e5)
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 sme_early_init(void)
181 {
182 	unsigned int i;
183 
184 	if (!sme_me_mask)
185 		return;
186 
187 	early_pmd_flags = __sme_set(early_pmd_flags);
188 
189 	__supported_pte_mask = __sme_set(__supported_pte_mask);
190 
191 	/* Update the protection map with memory encryption mask */
192 	for (i = 0; i < ARRAY_SIZE(protection_map); i++)
193 		protection_map[i] = pgprot_encrypted(protection_map[i]);
194 
195 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
196 		swiotlb_force = SWIOTLB_FORCE;
197 }
198 
199 void __init sev_setup_arch(void)
200 {
201 	phys_addr_t total_mem = memblock_phys_mem_size();
202 	unsigned long size;
203 
204 	if (!cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
205 		return;
206 
207 	/*
208 	 * For SEV, all DMA has to occur via shared/unencrypted pages.
209 	 * SEV uses SWIOTLB to make this happen without changing device
210 	 * drivers. However, depending on the workload being run, the
211 	 * default 64MB of SWIOTLB may not be enough and SWIOTLB may
212 	 * run out of buffers for DMA, resulting in I/O errors and/or
213 	 * performance degradation especially with high I/O workloads.
214 	 *
215 	 * Adjust the default size of SWIOTLB for SEV guests using
216 	 * a percentage of guest memory for SWIOTLB buffers.
217 	 * Also, as the SWIOTLB bounce buffer memory is allocated
218 	 * from low memory, ensure that the adjusted size is within
219 	 * the limits of low available memory.
220 	 *
221 	 * The percentage of guest memory used here for SWIOTLB buffers
222 	 * is more of an approximation of the static adjustment which
223 	 * 64MB for <1G, and ~128M to 256M for 1G-to-4G, i.e., the 6%
224 	 */
225 	size = total_mem * 6 / 100;
226 	size = clamp_val(size, IO_TLB_DEFAULT_SIZE, SZ_1G);
227 	swiotlb_adjust_size(size);
228 }
229 
230 static unsigned long pg_level_to_pfn(int level, pte_t *kpte, pgprot_t *ret_prot)
231 {
232 	unsigned long pfn = 0;
233 	pgprot_t prot;
234 
235 	switch (level) {
236 	case PG_LEVEL_4K:
237 		pfn = pte_pfn(*kpte);
238 		prot = pte_pgprot(*kpte);
239 		break;
240 	case PG_LEVEL_2M:
241 		pfn = pmd_pfn(*(pmd_t *)kpte);
242 		prot = pmd_pgprot(*(pmd_t *)kpte);
243 		break;
244 	case PG_LEVEL_1G:
245 		pfn = pud_pfn(*(pud_t *)kpte);
246 		prot = pud_pgprot(*(pud_t *)kpte);
247 		break;
248 	default:
249 		WARN_ONCE(1, "Invalid level for kpte\n");
250 		return 0;
251 	}
252 
253 	if (ret_prot)
254 		*ret_prot = prot;
255 
256 	return pfn;
257 }
258 
259 void notify_range_enc_status_changed(unsigned long vaddr, int npages, bool enc)
260 {
261 #ifdef CONFIG_PARAVIRT
262 	unsigned long sz = npages << PAGE_SHIFT;
263 	unsigned long vaddr_end = vaddr + sz;
264 
265 	while (vaddr < vaddr_end) {
266 		int psize, pmask, level;
267 		unsigned long pfn;
268 		pte_t *kpte;
269 
270 		kpte = lookup_address(vaddr, &level);
271 		if (!kpte || pte_none(*kpte)) {
272 			WARN_ONCE(1, "kpte lookup for vaddr\n");
273 			return;
274 		}
275 
276 		pfn = pg_level_to_pfn(level, kpte, NULL);
277 		if (!pfn)
278 			continue;
279 
280 		psize = page_level_size(level);
281 		pmask = page_level_mask(level);
282 
283 		notify_page_enc_status_changed(pfn, psize >> PAGE_SHIFT, enc);
284 
285 		vaddr = (vaddr & pmask) + psize;
286 	}
287 #endif
288 }
289 
290 static void __init __set_clr_pte_enc(pte_t *kpte, int level, bool enc)
291 {
292 	pgprot_t old_prot, new_prot;
293 	unsigned long pfn, pa, size;
294 	pte_t new_pte;
295 
296 	pfn = pg_level_to_pfn(level, kpte, &old_prot);
297 	if (!pfn)
298 		return;
299 
300 	new_prot = old_prot;
301 	if (enc)
302 		pgprot_val(new_prot) |= _PAGE_ENC;
303 	else
304 		pgprot_val(new_prot) &= ~_PAGE_ENC;
305 
306 	/* If prot is same then do nothing. */
307 	if (pgprot_val(old_prot) == pgprot_val(new_prot))
308 		return;
309 
310 	pa = pfn << PAGE_SHIFT;
311 	size = page_level_size(level);
312 
313 	/*
314 	 * We are going to perform in-place en-/decryption and change the
315 	 * physical page attribute from C=1 to C=0 or vice versa. Flush the
316 	 * caches to ensure that data gets accessed with the correct C-bit.
317 	 */
318 	clflush_cache_range(__va(pa), size);
319 
320 	/* Encrypt/decrypt the contents in-place */
321 	if (enc)
322 		sme_early_encrypt(pa, size);
323 	else
324 		sme_early_decrypt(pa, size);
325 
326 	/* Change the page encryption mask. */
327 	new_pte = pfn_pte(pfn, new_prot);
328 	set_pte_atomic(kpte, new_pte);
329 }
330 
331 static int __init early_set_memory_enc_dec(unsigned long vaddr,
332 					   unsigned long size, bool enc)
333 {
334 	unsigned long vaddr_end, vaddr_next, start;
335 	unsigned long psize, pmask;
336 	int split_page_size_mask;
337 	int level, ret;
338 	pte_t *kpte;
339 
340 	start = vaddr;
341 	vaddr_next = vaddr;
342 	vaddr_end = vaddr + size;
343 
344 	for (; vaddr < vaddr_end; vaddr = vaddr_next) {
345 		kpte = lookup_address(vaddr, &level);
346 		if (!kpte || pte_none(*kpte)) {
347 			ret = 1;
348 			goto out;
349 		}
350 
351 		if (level == PG_LEVEL_4K) {
352 			__set_clr_pte_enc(kpte, level, enc);
353 			vaddr_next = (vaddr & PAGE_MASK) + PAGE_SIZE;
354 			continue;
355 		}
356 
357 		psize = page_level_size(level);
358 		pmask = page_level_mask(level);
359 
360 		/*
361 		 * Check whether we can change the large page in one go.
362 		 * We request a split when the address is not aligned and
363 		 * the number of pages to set/clear encryption bit is smaller
364 		 * than the number of pages in the large page.
365 		 */
366 		if (vaddr == (vaddr & pmask) &&
367 		    ((vaddr_end - vaddr) >= psize)) {
368 			__set_clr_pte_enc(kpte, level, enc);
369 			vaddr_next = (vaddr & pmask) + psize;
370 			continue;
371 		}
372 
373 		/*
374 		 * The virtual address is part of a larger page, create the next
375 		 * level page table mapping (4K or 2M). If it is part of a 2M
376 		 * page then we request a split of the large page into 4K
377 		 * chunks. A 1GB large page is split into 2M pages, resp.
378 		 */
379 		if (level == PG_LEVEL_2M)
380 			split_page_size_mask = 0;
381 		else
382 			split_page_size_mask = 1 << PG_LEVEL_2M;
383 
384 		/*
385 		 * kernel_physical_mapping_change() does not flush the TLBs, so
386 		 * a TLB flush is required after we exit from the for loop.
387 		 */
388 		kernel_physical_mapping_change(__pa(vaddr & pmask),
389 					       __pa((vaddr_end & pmask) + psize),
390 					       split_page_size_mask);
391 	}
392 
393 	ret = 0;
394 
395 	notify_range_enc_status_changed(start, PAGE_ALIGN(size) >> PAGE_SHIFT, enc);
396 out:
397 	__flush_tlb_all();
398 	return ret;
399 }
400 
401 int __init early_set_memory_decrypted(unsigned long vaddr, unsigned long size)
402 {
403 	return early_set_memory_enc_dec(vaddr, size, false);
404 }
405 
406 int __init early_set_memory_encrypted(unsigned long vaddr, unsigned long size)
407 {
408 	return early_set_memory_enc_dec(vaddr, size, true);
409 }
410 
411 void __init early_set_mem_enc_dec_hypercall(unsigned long vaddr, int npages, bool enc)
412 {
413 	notify_range_enc_status_changed(vaddr, npages, enc);
414 }
415 
416 void __init mem_encrypt_free_decrypted_mem(void)
417 {
418 	unsigned long vaddr, vaddr_end, npages;
419 	int r;
420 
421 	vaddr = (unsigned long)__start_bss_decrypted_unused;
422 	vaddr_end = (unsigned long)__end_bss_decrypted;
423 	npages = (vaddr_end - vaddr) >> PAGE_SHIFT;
424 
425 	/*
426 	 * The unused memory range was mapped decrypted, change the encryption
427 	 * attribute from decrypted to encrypted before freeing it.
428 	 */
429 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
430 		r = set_memory_encrypted(vaddr, npages);
431 		if (r) {
432 			pr_warn("failed to free unused decrypted pages\n");
433 			return;
434 		}
435 	}
436 
437 	free_init_pages("unused decrypted", vaddr, vaddr_end);
438 }
439