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