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