1 /*
2  * AMD Memory Encryption Support
3  *
4  * Copyright (C) 2016 Advanced Micro Devices, Inc.
5  *
6  * Author: Tom Lendacky <thomas.lendacky@amd.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as
10  * published by the Free Software Foundation.
11  */
12 
13 #define DISABLE_BRANCH_PROFILING
14 
15 /*
16  * Since we're dealing with identity mappings, physical and virtual
17  * addresses are the same, so override these defines which are ultimately
18  * used by the headers in misc.h.
19  */
20 #define __pa(x)  ((unsigned long)(x))
21 #define __va(x)  ((void *)((unsigned long)(x)))
22 
23 /*
24  * Special hack: we have to be careful, because no indirections are
25  * allowed here, and paravirt_ops is a kind of one. As it will only run in
26  * baremetal anyway, we just keep it from happening. (This list needs to
27  * be extended when new paravirt and debugging variants are added.)
28  */
29 #undef CONFIG_PARAVIRT
30 #undef CONFIG_PARAVIRT_XXL
31 #undef CONFIG_PARAVIRT_SPINLOCKS
32 
33 #include <linux/kernel.h>
34 #include <linux/mm.h>
35 #include <linux/mem_encrypt.h>
36 
37 #include <asm/setup.h>
38 #include <asm/sections.h>
39 #include <asm/cmdline.h>
40 
41 #include "mm_internal.h"
42 
43 #define PGD_FLAGS		_KERNPG_TABLE_NOENC
44 #define P4D_FLAGS		_KERNPG_TABLE_NOENC
45 #define PUD_FLAGS		_KERNPG_TABLE_NOENC
46 #define PMD_FLAGS		_KERNPG_TABLE_NOENC
47 
48 #define PMD_FLAGS_LARGE		(__PAGE_KERNEL_LARGE_EXEC & ~_PAGE_GLOBAL)
49 
50 #define PMD_FLAGS_DEC		PMD_FLAGS_LARGE
51 #define PMD_FLAGS_DEC_WP	((PMD_FLAGS_DEC & ~_PAGE_CACHE_MASK) | \
52 				 (_PAGE_PAT | _PAGE_PWT))
53 
54 #define PMD_FLAGS_ENC		(PMD_FLAGS_LARGE | _PAGE_ENC)
55 
56 #define PTE_FLAGS		(__PAGE_KERNEL_EXEC & ~_PAGE_GLOBAL)
57 
58 #define PTE_FLAGS_DEC		PTE_FLAGS
59 #define PTE_FLAGS_DEC_WP	((PTE_FLAGS_DEC & ~_PAGE_CACHE_MASK) | \
60 				 (_PAGE_PAT | _PAGE_PWT))
61 
62 #define PTE_FLAGS_ENC		(PTE_FLAGS | _PAGE_ENC)
63 
64 struct sme_populate_pgd_data {
65 	void    *pgtable_area;
66 	pgd_t   *pgd;
67 
68 	pmdval_t pmd_flags;
69 	pteval_t pte_flags;
70 	unsigned long paddr;
71 
72 	unsigned long vaddr;
73 	unsigned long vaddr_end;
74 };
75 
76 static char sme_cmdline_arg[] __initdata = "mem_encrypt";
77 static char sme_cmdline_on[]  __initdata = "on";
78 static char sme_cmdline_off[] __initdata = "off";
79 
80 static void __init sme_clear_pgd(struct sme_populate_pgd_data *ppd)
81 {
82 	unsigned long pgd_start, pgd_end, pgd_size;
83 	pgd_t *pgd_p;
84 
85 	pgd_start = ppd->vaddr & PGDIR_MASK;
86 	pgd_end = ppd->vaddr_end & PGDIR_MASK;
87 
88 	pgd_size = (((pgd_end - pgd_start) / PGDIR_SIZE) + 1) * sizeof(pgd_t);
89 
90 	pgd_p = ppd->pgd + pgd_index(ppd->vaddr);
91 
92 	memset(pgd_p, 0, pgd_size);
93 }
94 
95 static pud_t __init *sme_prepare_pgd(struct sme_populate_pgd_data *ppd)
96 {
97 	pgd_t *pgd;
98 	p4d_t *p4d;
99 	pud_t *pud;
100 	pmd_t *pmd;
101 
102 	pgd = ppd->pgd + pgd_index(ppd->vaddr);
103 	if (pgd_none(*pgd)) {
104 		p4d = ppd->pgtable_area;
105 		memset(p4d, 0, sizeof(*p4d) * PTRS_PER_P4D);
106 		ppd->pgtable_area += sizeof(*p4d) * PTRS_PER_P4D;
107 		set_pgd(pgd, __pgd(PGD_FLAGS | __pa(p4d)));
108 	}
109 
110 	p4d = p4d_offset(pgd, ppd->vaddr);
111 	if (p4d_none(*p4d)) {
112 		pud = ppd->pgtable_area;
113 		memset(pud, 0, sizeof(*pud) * PTRS_PER_PUD);
114 		ppd->pgtable_area += sizeof(*pud) * PTRS_PER_PUD;
115 		set_p4d(p4d, __p4d(P4D_FLAGS | __pa(pud)));
116 	}
117 
118 	pud = pud_offset(p4d, ppd->vaddr);
119 	if (pud_none(*pud)) {
120 		pmd = ppd->pgtable_area;
121 		memset(pmd, 0, sizeof(*pmd) * PTRS_PER_PMD);
122 		ppd->pgtable_area += sizeof(*pmd) * PTRS_PER_PMD;
123 		set_pud(pud, __pud(PUD_FLAGS | __pa(pmd)));
124 	}
125 
126 	if (pud_large(*pud))
127 		return NULL;
128 
129 	return pud;
130 }
131 
132 static void __init sme_populate_pgd_large(struct sme_populate_pgd_data *ppd)
133 {
134 	pud_t *pud;
135 	pmd_t *pmd;
136 
137 	pud = sme_prepare_pgd(ppd);
138 	if (!pud)
139 		return;
140 
141 	pmd = pmd_offset(pud, ppd->vaddr);
142 	if (pmd_large(*pmd))
143 		return;
144 
145 	set_pmd(pmd, __pmd(ppd->paddr | ppd->pmd_flags));
146 }
147 
148 static void __init sme_populate_pgd(struct sme_populate_pgd_data *ppd)
149 {
150 	pud_t *pud;
151 	pmd_t *pmd;
152 	pte_t *pte;
153 
154 	pud = sme_prepare_pgd(ppd);
155 	if (!pud)
156 		return;
157 
158 	pmd = pmd_offset(pud, ppd->vaddr);
159 	if (pmd_none(*pmd)) {
160 		pte = ppd->pgtable_area;
161 		memset(pte, 0, sizeof(*pte) * PTRS_PER_PTE);
162 		ppd->pgtable_area += sizeof(*pte) * PTRS_PER_PTE;
163 		set_pmd(pmd, __pmd(PMD_FLAGS | __pa(pte)));
164 	}
165 
166 	if (pmd_large(*pmd))
167 		return;
168 
169 	pte = pte_offset_map(pmd, ppd->vaddr);
170 	if (pte_none(*pte))
171 		set_pte(pte, __pte(ppd->paddr | ppd->pte_flags));
172 }
173 
174 static void __init __sme_map_range_pmd(struct sme_populate_pgd_data *ppd)
175 {
176 	while (ppd->vaddr < ppd->vaddr_end) {
177 		sme_populate_pgd_large(ppd);
178 
179 		ppd->vaddr += PMD_PAGE_SIZE;
180 		ppd->paddr += PMD_PAGE_SIZE;
181 	}
182 }
183 
184 static void __init __sme_map_range_pte(struct sme_populate_pgd_data *ppd)
185 {
186 	while (ppd->vaddr < ppd->vaddr_end) {
187 		sme_populate_pgd(ppd);
188 
189 		ppd->vaddr += PAGE_SIZE;
190 		ppd->paddr += PAGE_SIZE;
191 	}
192 }
193 
194 static void __init __sme_map_range(struct sme_populate_pgd_data *ppd,
195 				   pmdval_t pmd_flags, pteval_t pte_flags)
196 {
197 	unsigned long vaddr_end;
198 
199 	ppd->pmd_flags = pmd_flags;
200 	ppd->pte_flags = pte_flags;
201 
202 	/* Save original end value since we modify the struct value */
203 	vaddr_end = ppd->vaddr_end;
204 
205 	/* If start is not 2MB aligned, create PTE entries */
206 	ppd->vaddr_end = ALIGN(ppd->vaddr, PMD_PAGE_SIZE);
207 	__sme_map_range_pte(ppd);
208 
209 	/* Create PMD entries */
210 	ppd->vaddr_end = vaddr_end & PMD_PAGE_MASK;
211 	__sme_map_range_pmd(ppd);
212 
213 	/* If end is not 2MB aligned, create PTE entries */
214 	ppd->vaddr_end = vaddr_end;
215 	__sme_map_range_pte(ppd);
216 }
217 
218 static void __init sme_map_range_encrypted(struct sme_populate_pgd_data *ppd)
219 {
220 	__sme_map_range(ppd, PMD_FLAGS_ENC, PTE_FLAGS_ENC);
221 }
222 
223 static void __init sme_map_range_decrypted(struct sme_populate_pgd_data *ppd)
224 {
225 	__sme_map_range(ppd, PMD_FLAGS_DEC, PTE_FLAGS_DEC);
226 }
227 
228 static void __init sme_map_range_decrypted_wp(struct sme_populate_pgd_data *ppd)
229 {
230 	__sme_map_range(ppd, PMD_FLAGS_DEC_WP, PTE_FLAGS_DEC_WP);
231 }
232 
233 static unsigned long __init sme_pgtable_calc(unsigned long len)
234 {
235 	unsigned long entries = 0, tables = 0;
236 
237 	/*
238 	 * Perform a relatively simplistic calculation of the pagetable
239 	 * entries that are needed. Those mappings will be covered mostly
240 	 * by 2MB PMD entries so we can conservatively calculate the required
241 	 * number of P4D, PUD and PMD structures needed to perform the
242 	 * mappings.  For mappings that are not 2MB aligned, PTE mappings
243 	 * would be needed for the start and end portion of the address range
244 	 * that fall outside of the 2MB alignment.  This results in, at most,
245 	 * two extra pages to hold PTE entries for each range that is mapped.
246 	 * Incrementing the count for each covers the case where the addresses
247 	 * cross entries.
248 	 */
249 
250 	/* PGDIR_SIZE is equal to P4D_SIZE on 4-level machine. */
251 	if (PTRS_PER_P4D > 1)
252 		entries += (DIV_ROUND_UP(len, PGDIR_SIZE) + 1) * sizeof(p4d_t) * PTRS_PER_P4D;
253 	entries += (DIV_ROUND_UP(len, P4D_SIZE) + 1) * sizeof(pud_t) * PTRS_PER_PUD;
254 	entries += (DIV_ROUND_UP(len, PUD_SIZE) + 1) * sizeof(pmd_t) * PTRS_PER_PMD;
255 	entries += 2 * sizeof(pte_t) * PTRS_PER_PTE;
256 
257 	/*
258 	 * Now calculate the added pagetable structures needed to populate
259 	 * the new pagetables.
260 	 */
261 
262 	if (PTRS_PER_P4D > 1)
263 		tables += DIV_ROUND_UP(entries, PGDIR_SIZE) * sizeof(p4d_t) * PTRS_PER_P4D;
264 	tables += DIV_ROUND_UP(entries, P4D_SIZE) * sizeof(pud_t) * PTRS_PER_PUD;
265 	tables += DIV_ROUND_UP(entries, PUD_SIZE) * sizeof(pmd_t) * PTRS_PER_PMD;
266 
267 	return entries + tables;
268 }
269 
270 void __init sme_encrypt_kernel(struct boot_params *bp)
271 {
272 	unsigned long workarea_start, workarea_end, workarea_len;
273 	unsigned long execute_start, execute_end, execute_len;
274 	unsigned long kernel_start, kernel_end, kernel_len;
275 	unsigned long initrd_start, initrd_end, initrd_len;
276 	struct sme_populate_pgd_data ppd;
277 	unsigned long pgtable_area_len;
278 	unsigned long decrypted_base;
279 
280 	if (!sme_active())
281 		return;
282 
283 	/*
284 	 * Prepare for encrypting the kernel and initrd by building new
285 	 * pagetables with the necessary attributes needed to encrypt the
286 	 * kernel in place.
287 	 *
288 	 *   One range of virtual addresses will map the memory occupied
289 	 *   by the kernel and initrd as encrypted.
290 	 *
291 	 *   Another range of virtual addresses will map the memory occupied
292 	 *   by the kernel and initrd as decrypted and write-protected.
293 	 *
294 	 *     The use of write-protect attribute will prevent any of the
295 	 *     memory from being cached.
296 	 */
297 
298 	/* Physical addresses gives us the identity mapped virtual addresses */
299 	kernel_start = __pa_symbol(_text);
300 	kernel_end = ALIGN(__pa_symbol(_end), PMD_PAGE_SIZE);
301 	kernel_len = kernel_end - kernel_start;
302 
303 	initrd_start = 0;
304 	initrd_end = 0;
305 	initrd_len = 0;
306 #ifdef CONFIG_BLK_DEV_INITRD
307 	initrd_len = (unsigned long)bp->hdr.ramdisk_size |
308 		     ((unsigned long)bp->ext_ramdisk_size << 32);
309 	if (initrd_len) {
310 		initrd_start = (unsigned long)bp->hdr.ramdisk_image |
311 			       ((unsigned long)bp->ext_ramdisk_image << 32);
312 		initrd_end = PAGE_ALIGN(initrd_start + initrd_len);
313 		initrd_len = initrd_end - initrd_start;
314 	}
315 #endif
316 
317 	/* Set the encryption workarea to be immediately after the kernel */
318 	workarea_start = kernel_end;
319 
320 	/*
321 	 * Calculate required number of workarea bytes needed:
322 	 *   executable encryption area size:
323 	 *     stack page (PAGE_SIZE)
324 	 *     encryption routine page (PAGE_SIZE)
325 	 *     intermediate copy buffer (PMD_PAGE_SIZE)
326 	 *   pagetable structures for the encryption of the kernel
327 	 *   pagetable structures for workarea (in case not currently mapped)
328 	 */
329 	execute_start = workarea_start;
330 	execute_end = execute_start + (PAGE_SIZE * 2) + PMD_PAGE_SIZE;
331 	execute_len = execute_end - execute_start;
332 
333 	/*
334 	 * One PGD for both encrypted and decrypted mappings and a set of
335 	 * PUDs and PMDs for each of the encrypted and decrypted mappings.
336 	 */
337 	pgtable_area_len = sizeof(pgd_t) * PTRS_PER_PGD;
338 	pgtable_area_len += sme_pgtable_calc(execute_end - kernel_start) * 2;
339 	if (initrd_len)
340 		pgtable_area_len += sme_pgtable_calc(initrd_len) * 2;
341 
342 	/* PUDs and PMDs needed in the current pagetables for the workarea */
343 	pgtable_area_len += sme_pgtable_calc(execute_len + pgtable_area_len);
344 
345 	/*
346 	 * The total workarea includes the executable encryption area and
347 	 * the pagetable area. The start of the workarea is already 2MB
348 	 * aligned, align the end of the workarea on a 2MB boundary so that
349 	 * we don't try to create/allocate PTE entries from the workarea
350 	 * before it is mapped.
351 	 */
352 	workarea_len = execute_len + pgtable_area_len;
353 	workarea_end = ALIGN(workarea_start + workarea_len, PMD_PAGE_SIZE);
354 
355 	/*
356 	 * Set the address to the start of where newly created pagetable
357 	 * structures (PGDs, PUDs and PMDs) will be allocated. New pagetable
358 	 * structures are created when the workarea is added to the current
359 	 * pagetables and when the new encrypted and decrypted kernel
360 	 * mappings are populated.
361 	 */
362 	ppd.pgtable_area = (void *)execute_end;
363 
364 	/*
365 	 * Make sure the current pagetable structure has entries for
366 	 * addressing the workarea.
367 	 */
368 	ppd.pgd = (pgd_t *)native_read_cr3_pa();
369 	ppd.paddr = workarea_start;
370 	ppd.vaddr = workarea_start;
371 	ppd.vaddr_end = workarea_end;
372 	sme_map_range_decrypted(&ppd);
373 
374 	/* Flush the TLB - no globals so cr3 is enough */
375 	native_write_cr3(__native_read_cr3());
376 
377 	/*
378 	 * A new pagetable structure is being built to allow for the kernel
379 	 * and initrd to be encrypted. It starts with an empty PGD that will
380 	 * then be populated with new PUDs and PMDs as the encrypted and
381 	 * decrypted kernel mappings are created.
382 	 */
383 	ppd.pgd = ppd.pgtable_area;
384 	memset(ppd.pgd, 0, sizeof(pgd_t) * PTRS_PER_PGD);
385 	ppd.pgtable_area += sizeof(pgd_t) * PTRS_PER_PGD;
386 
387 	/*
388 	 * A different PGD index/entry must be used to get different
389 	 * pagetable entries for the decrypted mapping. Choose the next
390 	 * PGD index and convert it to a virtual address to be used as
391 	 * the base of the mapping.
392 	 */
393 	decrypted_base = (pgd_index(workarea_end) + 1) & (PTRS_PER_PGD - 1);
394 	if (initrd_len) {
395 		unsigned long check_base;
396 
397 		check_base = (pgd_index(initrd_end) + 1) & (PTRS_PER_PGD - 1);
398 		decrypted_base = max(decrypted_base, check_base);
399 	}
400 	decrypted_base <<= PGDIR_SHIFT;
401 
402 	/* Add encrypted kernel (identity) mappings */
403 	ppd.paddr = kernel_start;
404 	ppd.vaddr = kernel_start;
405 	ppd.vaddr_end = kernel_end;
406 	sme_map_range_encrypted(&ppd);
407 
408 	/* Add decrypted, write-protected kernel (non-identity) mappings */
409 	ppd.paddr = kernel_start;
410 	ppd.vaddr = kernel_start + decrypted_base;
411 	ppd.vaddr_end = kernel_end + decrypted_base;
412 	sme_map_range_decrypted_wp(&ppd);
413 
414 	if (initrd_len) {
415 		/* Add encrypted initrd (identity) mappings */
416 		ppd.paddr = initrd_start;
417 		ppd.vaddr = initrd_start;
418 		ppd.vaddr_end = initrd_end;
419 		sme_map_range_encrypted(&ppd);
420 		/*
421 		 * Add decrypted, write-protected initrd (non-identity) mappings
422 		 */
423 		ppd.paddr = initrd_start;
424 		ppd.vaddr = initrd_start + decrypted_base;
425 		ppd.vaddr_end = initrd_end + decrypted_base;
426 		sme_map_range_decrypted_wp(&ppd);
427 	}
428 
429 	/* Add decrypted workarea mappings to both kernel mappings */
430 	ppd.paddr = workarea_start;
431 	ppd.vaddr = workarea_start;
432 	ppd.vaddr_end = workarea_end;
433 	sme_map_range_decrypted(&ppd);
434 
435 	ppd.paddr = workarea_start;
436 	ppd.vaddr = workarea_start + decrypted_base;
437 	ppd.vaddr_end = workarea_end + decrypted_base;
438 	sme_map_range_decrypted(&ppd);
439 
440 	/* Perform the encryption */
441 	sme_encrypt_execute(kernel_start, kernel_start + decrypted_base,
442 			    kernel_len, workarea_start, (unsigned long)ppd.pgd);
443 
444 	if (initrd_len)
445 		sme_encrypt_execute(initrd_start, initrd_start + decrypted_base,
446 				    initrd_len, workarea_start,
447 				    (unsigned long)ppd.pgd);
448 
449 	/*
450 	 * At this point we are running encrypted.  Remove the mappings for
451 	 * the decrypted areas - all that is needed for this is to remove
452 	 * the PGD entry/entries.
453 	 */
454 	ppd.vaddr = kernel_start + decrypted_base;
455 	ppd.vaddr_end = kernel_end + decrypted_base;
456 	sme_clear_pgd(&ppd);
457 
458 	if (initrd_len) {
459 		ppd.vaddr = initrd_start + decrypted_base;
460 		ppd.vaddr_end = initrd_end + decrypted_base;
461 		sme_clear_pgd(&ppd);
462 	}
463 
464 	ppd.vaddr = workarea_start + decrypted_base;
465 	ppd.vaddr_end = workarea_end + decrypted_base;
466 	sme_clear_pgd(&ppd);
467 
468 	/* Flush the TLB - no globals so cr3 is enough */
469 	native_write_cr3(__native_read_cr3());
470 }
471 
472 void __init sme_enable(struct boot_params *bp)
473 {
474 	const char *cmdline_ptr, *cmdline_arg, *cmdline_on, *cmdline_off;
475 	unsigned int eax, ebx, ecx, edx;
476 	unsigned long feature_mask;
477 	bool active_by_default;
478 	unsigned long me_mask;
479 	char buffer[16];
480 	u64 msr;
481 
482 	/* Check for the SME/SEV support leaf */
483 	eax = 0x80000000;
484 	ecx = 0;
485 	native_cpuid(&eax, &ebx, &ecx, &edx);
486 	if (eax < 0x8000001f)
487 		return;
488 
489 #define AMD_SME_BIT	BIT(0)
490 #define AMD_SEV_BIT	BIT(1)
491 	/*
492 	 * Set the feature mask (SME or SEV) based on whether we are
493 	 * running under a hypervisor.
494 	 */
495 	eax = 1;
496 	ecx = 0;
497 	native_cpuid(&eax, &ebx, &ecx, &edx);
498 	feature_mask = (ecx & BIT(31)) ? AMD_SEV_BIT : AMD_SME_BIT;
499 
500 	/*
501 	 * Check for the SME/SEV feature:
502 	 *   CPUID Fn8000_001F[EAX]
503 	 *   - Bit 0 - Secure Memory Encryption support
504 	 *   - Bit 1 - Secure Encrypted Virtualization support
505 	 *   CPUID Fn8000_001F[EBX]
506 	 *   - Bits 5:0 - Pagetable bit position used to indicate encryption
507 	 */
508 	eax = 0x8000001f;
509 	ecx = 0;
510 	native_cpuid(&eax, &ebx, &ecx, &edx);
511 	if (!(eax & feature_mask))
512 		return;
513 
514 	me_mask = 1UL << (ebx & 0x3f);
515 
516 	/* Check if memory encryption is enabled */
517 	if (feature_mask == AMD_SME_BIT) {
518 		/* For SME, check the SYSCFG MSR */
519 		msr = __rdmsr(MSR_K8_SYSCFG);
520 		if (!(msr & MSR_K8_SYSCFG_MEM_ENCRYPT))
521 			return;
522 	} else {
523 		/* For SEV, check the SEV MSR */
524 		msr = __rdmsr(MSR_AMD64_SEV);
525 		if (!(msr & MSR_AMD64_SEV_ENABLED))
526 			return;
527 
528 		/* SEV state cannot be controlled by a command line option */
529 		sme_me_mask = me_mask;
530 		sev_enabled = true;
531 		physical_mask &= ~sme_me_mask;
532 		return;
533 	}
534 
535 	/*
536 	 * Fixups have not been applied to phys_base yet and we're running
537 	 * identity mapped, so we must obtain the address to the SME command
538 	 * line argument data using rip-relative addressing.
539 	 */
540 	asm ("lea sme_cmdline_arg(%%rip), %0"
541 	     : "=r" (cmdline_arg)
542 	     : "p" (sme_cmdline_arg));
543 	asm ("lea sme_cmdline_on(%%rip), %0"
544 	     : "=r" (cmdline_on)
545 	     : "p" (sme_cmdline_on));
546 	asm ("lea sme_cmdline_off(%%rip), %0"
547 	     : "=r" (cmdline_off)
548 	     : "p" (sme_cmdline_off));
549 
550 	if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT))
551 		active_by_default = true;
552 	else
553 		active_by_default = false;
554 
555 	cmdline_ptr = (const char *)((u64)bp->hdr.cmd_line_ptr |
556 				     ((u64)bp->ext_cmd_line_ptr << 32));
557 
558 	cmdline_find_option(cmdline_ptr, cmdline_arg, buffer, sizeof(buffer));
559 
560 	if (!strncmp(buffer, cmdline_on, sizeof(buffer)))
561 		sme_me_mask = me_mask;
562 	else if (!strncmp(buffer, cmdline_off, sizeof(buffer)))
563 		sme_me_mask = 0;
564 	else
565 		sme_me_mask = active_by_default ? me_mask : 0;
566 
567 	physical_mask &= ~sme_me_mask;
568 }
569