xref: /OK3568_Linux_fs/kernel/arch/x86/kernel/sev-es.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AMD Memory Encryption Support
4  *
5  * Copyright (C) 2019 SUSE
6  *
7  * Author: Joerg Roedel <jroedel@suse.de>
8  */
9 
10 #define pr_fmt(fmt)	"SEV-ES: " fmt
11 
12 #include <linux/sched/debug.h>	/* For show_regs() */
13 #include <linux/percpu-defs.h>
14 #include <linux/mem_encrypt.h>
15 #include <linux/printk.h>
16 #include <linux/mm_types.h>
17 #include <linux/set_memory.h>
18 #include <linux/memblock.h>
19 #include <linux/kernel.h>
20 #include <linux/mm.h>
21 
22 #include <asm/cpu_entry_area.h>
23 #include <asm/stacktrace.h>
24 #include <asm/sev-es.h>
25 #include <asm/insn-eval.h>
26 #include <asm/fpu/internal.h>
27 #include <asm/processor.h>
28 #include <asm/realmode.h>
29 #include <asm/traps.h>
30 #include <asm/svm.h>
31 #include <asm/smp.h>
32 #include <asm/cpu.h>
33 
34 #define DR7_RESET_VALUE        0x400
35 
36 /* For early boot hypervisor communication in SEV-ES enabled guests */
37 static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
38 
39 /*
40  * Needs to be in the .data section because we need it NULL before bss is
41  * cleared
42  */
43 static struct ghcb __initdata *boot_ghcb;
44 
45 /* #VC handler runtime per-CPU data */
46 struct sev_es_runtime_data {
47 	struct ghcb ghcb_page;
48 
49 	/*
50 	 * Reserve one page per CPU as backup storage for the unencrypted GHCB.
51 	 * It is needed when an NMI happens while the #VC handler uses the real
52 	 * GHCB, and the NMI handler itself is causing another #VC exception. In
53 	 * that case the GHCB content of the first handler needs to be backed up
54 	 * and restored.
55 	 */
56 	struct ghcb backup_ghcb;
57 
58 	/*
59 	 * Mark the per-cpu GHCBs as in-use to detect nested #VC exceptions.
60 	 * There is no need for it to be atomic, because nothing is written to
61 	 * the GHCB between the read and the write of ghcb_active. So it is safe
62 	 * to use it when a nested #VC exception happens before the write.
63 	 *
64 	 * This is necessary for example in the #VC->NMI->#VC case when the NMI
65 	 * happens while the first #VC handler uses the GHCB. When the NMI code
66 	 * raises a second #VC handler it might overwrite the contents of the
67 	 * GHCB written by the first handler. To avoid this the content of the
68 	 * GHCB is saved and restored when the GHCB is detected to be in use
69 	 * already.
70 	 */
71 	bool ghcb_active;
72 	bool backup_ghcb_active;
73 
74 	/*
75 	 * Cached DR7 value - write it on DR7 writes and return it on reads.
76 	 * That value will never make it to the real hardware DR7 as debugging
77 	 * is currently unsupported in SEV-ES guests.
78 	 */
79 	unsigned long dr7;
80 };
81 
82 struct ghcb_state {
83 	struct ghcb *ghcb;
84 };
85 
86 static DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
87 DEFINE_STATIC_KEY_FALSE(sev_es_enable_key);
88 
89 /* Needed in vc_early_forward_exception */
90 void do_early_exception(struct pt_regs *regs, int trapnr);
91 
on_vc_stack(struct pt_regs * regs)92 static __always_inline bool on_vc_stack(struct pt_regs *regs)
93 {
94 	unsigned long sp = regs->sp;
95 
96 	/* User-mode RSP is not trusted */
97 	if (user_mode(regs))
98 		return false;
99 
100 	/* SYSCALL gap still has user-mode RSP */
101 	if (ip_within_syscall_gap(regs))
102 		return false;
103 
104 	return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
105 }
106 
107 /*
108  * This function handles the case when an NMI is raised in the #VC exception
109  * handler entry code. In this case, the IST entry for #VC must be adjusted, so
110  * that any subsequent #VC exception will not overwrite the stack contents of the
111  * interrupted #VC handler.
112  *
113  * The IST entry is adjusted unconditionally so that it can be also be
114  * unconditionally adjusted back in sev_es_ist_exit(). Otherwise a nested
115  * sev_es_ist_exit() call may adjust back the IST entry too early.
116  */
__sev_es_ist_enter(struct pt_regs * regs)117 void noinstr __sev_es_ist_enter(struct pt_regs *regs)
118 {
119 	unsigned long old_ist, new_ist;
120 
121 	/* Read old IST entry */
122 	old_ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
123 
124 	/* Make room on the IST stack */
125 	if (on_vc_stack(regs))
126 		new_ist = ALIGN_DOWN(regs->sp, 8) - sizeof(old_ist);
127 	else
128 		new_ist = old_ist - sizeof(old_ist);
129 
130 	/* Store old IST entry */
131 	*(unsigned long *)new_ist = old_ist;
132 
133 	/* Set new IST entry */
134 	this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], new_ist);
135 }
136 
__sev_es_ist_exit(void)137 void noinstr __sev_es_ist_exit(void)
138 {
139 	unsigned long ist;
140 
141 	/* Read IST entry */
142 	ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
143 
144 	if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
145 		return;
146 
147 	/* Read back old IST entry and write it to the TSS */
148 	this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], *(unsigned long *)ist);
149 }
150 
151 /*
152  * Nothing shall interrupt this code path while holding the per-CPU
153  * GHCB. The backup GHCB is only for NMIs interrupting this path.
154  *
155  * Callers must disable local interrupts around it.
156  */
__sev_get_ghcb(struct ghcb_state * state)157 static noinstr struct ghcb *__sev_get_ghcb(struct ghcb_state *state)
158 {
159 	struct sev_es_runtime_data *data;
160 	struct ghcb *ghcb;
161 
162 	WARN_ON(!irqs_disabled());
163 
164 	data = this_cpu_read(runtime_data);
165 	ghcb = &data->ghcb_page;
166 
167 	if (unlikely(data->ghcb_active)) {
168 		/* GHCB is already in use - save its contents */
169 
170 		if (unlikely(data->backup_ghcb_active)) {
171 			/*
172 			 * Backup-GHCB is also already in use. There is no way
173 			 * to continue here so just kill the machine. To make
174 			 * panic() work, mark GHCBs inactive so that messages
175 			 * can be printed out.
176 			 */
177 			data->ghcb_active        = false;
178 			data->backup_ghcb_active = false;
179 
180 			instrumentation_begin();
181 			panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
182 			instrumentation_end();
183 		}
184 
185 		/* Mark backup_ghcb active before writing to it */
186 		data->backup_ghcb_active = true;
187 
188 		state->ghcb = &data->backup_ghcb;
189 
190 		/* Backup GHCB content */
191 		*state->ghcb = *ghcb;
192 	} else {
193 		state->ghcb = NULL;
194 		data->ghcb_active = true;
195 	}
196 
197 	return ghcb;
198 }
199 
200 /* Needed in vc_early_forward_exception */
201 void do_early_exception(struct pt_regs *regs, int trapnr);
202 
sev_es_rd_ghcb_msr(void)203 static inline u64 sev_es_rd_ghcb_msr(void)
204 {
205 	return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
206 }
207 
sev_es_wr_ghcb_msr(u64 val)208 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
209 {
210 	u32 low, high;
211 
212 	low  = (u32)(val);
213 	high = (u32)(val >> 32);
214 
215 	native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
216 }
217 
vc_fetch_insn_kernel(struct es_em_ctxt * ctxt,unsigned char * buffer)218 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
219 				unsigned char *buffer)
220 {
221 	return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
222 }
223 
vc_decode_insn(struct es_em_ctxt * ctxt)224 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
225 {
226 	char buffer[MAX_INSN_SIZE];
227 	enum es_result ret;
228 	int res;
229 
230 	if (user_mode(ctxt->regs)) {
231 		res = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
232 		if (!res) {
233 			ctxt->fi.vector     = X86_TRAP_PF;
234 			ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
235 			ctxt->fi.cr2        = ctxt->regs->ip;
236 			return ES_EXCEPTION;
237 		}
238 
239 		if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, res))
240 			return ES_DECODE_FAILED;
241 	} else {
242 		res = vc_fetch_insn_kernel(ctxt, buffer);
243 		if (res) {
244 			ctxt->fi.vector     = X86_TRAP_PF;
245 			ctxt->fi.error_code = X86_PF_INSTR;
246 			ctxt->fi.cr2        = ctxt->regs->ip;
247 			return ES_EXCEPTION;
248 		}
249 
250 		insn_init(&ctxt->insn, buffer, MAX_INSN_SIZE - res, 1);
251 		insn_get_length(&ctxt->insn);
252 	}
253 
254 	ret = ctxt->insn.immediate.got ? ES_OK : ES_DECODE_FAILED;
255 
256 	return ret;
257 }
258 
vc_write_mem(struct es_em_ctxt * ctxt,char * dst,char * buf,size_t size)259 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
260 				   char *dst, char *buf, size_t size)
261 {
262 	unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
263 
264 	/*
265 	 * This function uses __put_user() independent of whether kernel or user
266 	 * memory is accessed. This works fine because __put_user() does no
267 	 * sanity checks of the pointer being accessed. All that it does is
268 	 * to report when the access failed.
269 	 *
270 	 * Also, this function runs in atomic context, so __put_user() is not
271 	 * allowed to sleep. The page-fault handler detects that it is running
272 	 * in atomic context and will not try to take mmap_sem and handle the
273 	 * fault, so additional pagefault_enable()/disable() calls are not
274 	 * needed.
275 	 *
276 	 * The access can't be done via copy_to_user() here because
277 	 * vc_write_mem() must not use string instructions to access unsafe
278 	 * memory. The reason is that MOVS is emulated by the #VC handler by
279 	 * splitting the move up into a read and a write and taking a nested #VC
280 	 * exception on whatever of them is the MMIO access. Using string
281 	 * instructions here would cause infinite nesting.
282 	 */
283 	switch (size) {
284 	case 1: {
285 		u8 d1;
286 		u8 __user *target = (u8 __user *)dst;
287 
288 		memcpy(&d1, buf, 1);
289 		if (__put_user(d1, target))
290 			goto fault;
291 		break;
292 	}
293 	case 2: {
294 		u16 d2;
295 		u16 __user *target = (u16 __user *)dst;
296 
297 		memcpy(&d2, buf, 2);
298 		if (__put_user(d2, target))
299 			goto fault;
300 		break;
301 	}
302 	case 4: {
303 		u32 d4;
304 		u32 __user *target = (u32 __user *)dst;
305 
306 		memcpy(&d4, buf, 4);
307 		if (__put_user(d4, target))
308 			goto fault;
309 		break;
310 	}
311 	case 8: {
312 		u64 d8;
313 		u64 __user *target = (u64 __user *)dst;
314 
315 		memcpy(&d8, buf, 8);
316 		if (__put_user(d8, target))
317 			goto fault;
318 		break;
319 	}
320 	default:
321 		WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
322 		return ES_UNSUPPORTED;
323 	}
324 
325 	return ES_OK;
326 
327 fault:
328 	if (user_mode(ctxt->regs))
329 		error_code |= X86_PF_USER;
330 
331 	ctxt->fi.vector = X86_TRAP_PF;
332 	ctxt->fi.error_code = error_code;
333 	ctxt->fi.cr2 = (unsigned long)dst;
334 
335 	return ES_EXCEPTION;
336 }
337 
vc_read_mem(struct es_em_ctxt * ctxt,char * src,char * buf,size_t size)338 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
339 				  char *src, char *buf, size_t size)
340 {
341 	unsigned long error_code = X86_PF_PROT;
342 
343 	/*
344 	 * This function uses __get_user() independent of whether kernel or user
345 	 * memory is accessed. This works fine because __get_user() does no
346 	 * sanity checks of the pointer being accessed. All that it does is
347 	 * to report when the access failed.
348 	 *
349 	 * Also, this function runs in atomic context, so __get_user() is not
350 	 * allowed to sleep. The page-fault handler detects that it is running
351 	 * in atomic context and will not try to take mmap_sem and handle the
352 	 * fault, so additional pagefault_enable()/disable() calls are not
353 	 * needed.
354 	 *
355 	 * The access can't be done via copy_from_user() here because
356 	 * vc_read_mem() must not use string instructions to access unsafe
357 	 * memory. The reason is that MOVS is emulated by the #VC handler by
358 	 * splitting the move up into a read and a write and taking a nested #VC
359 	 * exception on whatever of them is the MMIO access. Using string
360 	 * instructions here would cause infinite nesting.
361 	 */
362 	switch (size) {
363 	case 1: {
364 		u8 d1;
365 		u8 __user *s = (u8 __user *)src;
366 
367 		if (__get_user(d1, s))
368 			goto fault;
369 		memcpy(buf, &d1, 1);
370 		break;
371 	}
372 	case 2: {
373 		u16 d2;
374 		u16 __user *s = (u16 __user *)src;
375 
376 		if (__get_user(d2, s))
377 			goto fault;
378 		memcpy(buf, &d2, 2);
379 		break;
380 	}
381 	case 4: {
382 		u32 d4;
383 		u32 __user *s = (u32 __user *)src;
384 
385 		if (__get_user(d4, s))
386 			goto fault;
387 		memcpy(buf, &d4, 4);
388 		break;
389 	}
390 	case 8: {
391 		u64 d8;
392 		u64 __user *s = (u64 __user *)src;
393 		if (__get_user(d8, s))
394 			goto fault;
395 		memcpy(buf, &d8, 8);
396 		break;
397 	}
398 	default:
399 		WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
400 		return ES_UNSUPPORTED;
401 	}
402 
403 	return ES_OK;
404 
405 fault:
406 	if (user_mode(ctxt->regs))
407 		error_code |= X86_PF_USER;
408 
409 	ctxt->fi.vector = X86_TRAP_PF;
410 	ctxt->fi.error_code = error_code;
411 	ctxt->fi.cr2 = (unsigned long)src;
412 
413 	return ES_EXCEPTION;
414 }
415 
vc_slow_virt_to_phys(struct ghcb * ghcb,struct es_em_ctxt * ctxt,unsigned long vaddr,phys_addr_t * paddr)416 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
417 					   unsigned long vaddr, phys_addr_t *paddr)
418 {
419 	unsigned long va = (unsigned long)vaddr;
420 	unsigned int level;
421 	phys_addr_t pa;
422 	pgd_t *pgd;
423 	pte_t *pte;
424 
425 	pgd = __va(read_cr3_pa());
426 	pgd = &pgd[pgd_index(va)];
427 	pte = lookup_address_in_pgd(pgd, va, &level);
428 	if (!pte) {
429 		ctxt->fi.vector     = X86_TRAP_PF;
430 		ctxt->fi.cr2        = vaddr;
431 		ctxt->fi.error_code = 0;
432 
433 		if (user_mode(ctxt->regs))
434 			ctxt->fi.error_code |= X86_PF_USER;
435 
436 		return ES_EXCEPTION;
437 	}
438 
439 	if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
440 		/* Emulated MMIO to/from encrypted memory not supported */
441 		return ES_UNSUPPORTED;
442 
443 	pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
444 	pa |= va & ~page_level_mask(level);
445 
446 	*paddr = pa;
447 
448 	return ES_OK;
449 }
450 
451 /* Include code shared with pre-decompression boot stage */
452 #include "sev-es-shared.c"
453 
__sev_put_ghcb(struct ghcb_state * state)454 static noinstr void __sev_put_ghcb(struct ghcb_state *state)
455 {
456 	struct sev_es_runtime_data *data;
457 	struct ghcb *ghcb;
458 
459 	WARN_ON(!irqs_disabled());
460 
461 	data = this_cpu_read(runtime_data);
462 	ghcb = &data->ghcb_page;
463 
464 	if (state->ghcb) {
465 		/* Restore GHCB from Backup */
466 		*ghcb = *state->ghcb;
467 		data->backup_ghcb_active = false;
468 		state->ghcb = NULL;
469 	} else {
470 		/*
471 		 * Invalidate the GHCB so a VMGEXIT instruction issued
472 		 * from userspace won't appear to be valid.
473 		 */
474 		vc_ghcb_invalidate(ghcb);
475 		data->ghcb_active = false;
476 	}
477 }
478 
__sev_es_nmi_complete(void)479 void noinstr __sev_es_nmi_complete(void)
480 {
481 	struct ghcb_state state;
482 	struct ghcb *ghcb;
483 
484 	ghcb = __sev_get_ghcb(&state);
485 
486 	vc_ghcb_invalidate(ghcb);
487 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
488 	ghcb_set_sw_exit_info_1(ghcb, 0);
489 	ghcb_set_sw_exit_info_2(ghcb, 0);
490 
491 	sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
492 	VMGEXIT();
493 
494 	__sev_put_ghcb(&state);
495 }
496 
get_jump_table_addr(void)497 static u64 get_jump_table_addr(void)
498 {
499 	struct ghcb_state state;
500 	unsigned long flags;
501 	struct ghcb *ghcb;
502 	u64 ret = 0;
503 
504 	local_irq_save(flags);
505 
506 	ghcb = __sev_get_ghcb(&state);
507 
508 	vc_ghcb_invalidate(ghcb);
509 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
510 	ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
511 	ghcb_set_sw_exit_info_2(ghcb, 0);
512 
513 	sev_es_wr_ghcb_msr(__pa(ghcb));
514 	VMGEXIT();
515 
516 	if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
517 	    ghcb_sw_exit_info_2_is_valid(ghcb))
518 		ret = ghcb->save.sw_exit_info_2;
519 
520 	__sev_put_ghcb(&state);
521 
522 	local_irq_restore(flags);
523 
524 	return ret;
525 }
526 
sev_es_setup_ap_jump_table(struct real_mode_header * rmh)527 int sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
528 {
529 	u16 startup_cs, startup_ip;
530 	phys_addr_t jump_table_pa;
531 	u64 jump_table_addr;
532 	u16 __iomem *jump_table;
533 
534 	jump_table_addr = get_jump_table_addr();
535 
536 	/* On UP guests there is no jump table so this is not a failure */
537 	if (!jump_table_addr)
538 		return 0;
539 
540 	/* Check if AP Jump Table is page-aligned */
541 	if (jump_table_addr & ~PAGE_MASK)
542 		return -EINVAL;
543 
544 	jump_table_pa = jump_table_addr & PAGE_MASK;
545 
546 	startup_cs = (u16)(rmh->trampoline_start >> 4);
547 	startup_ip = (u16)(rmh->sev_es_trampoline_start -
548 			   rmh->trampoline_start);
549 
550 	jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
551 	if (!jump_table)
552 		return -EIO;
553 
554 	writew(startup_ip, &jump_table[0]);
555 	writew(startup_cs, &jump_table[1]);
556 
557 	iounmap(jump_table);
558 
559 	return 0;
560 }
561 
562 /*
563  * This is needed by the OVMF UEFI firmware which will use whatever it finds in
564  * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
565  * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
566  */
sev_es_efi_map_ghcbs(pgd_t * pgd)567 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
568 {
569 	struct sev_es_runtime_data *data;
570 	unsigned long address, pflags;
571 	int cpu;
572 	u64 pfn;
573 
574 	if (!sev_es_active())
575 		return 0;
576 
577 	pflags = _PAGE_NX | _PAGE_RW;
578 
579 	for_each_possible_cpu(cpu) {
580 		data = per_cpu(runtime_data, cpu);
581 
582 		address = __pa(&data->ghcb_page);
583 		pfn = address >> PAGE_SHIFT;
584 
585 		if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
586 			return 1;
587 	}
588 
589 	return 0;
590 }
591 
vc_handle_msr(struct ghcb * ghcb,struct es_em_ctxt * ctxt)592 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
593 {
594 	struct pt_regs *regs = ctxt->regs;
595 	enum es_result ret;
596 	u64 exit_info_1;
597 
598 	/* Is it a WRMSR? */
599 	exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
600 
601 	ghcb_set_rcx(ghcb, regs->cx);
602 	if (exit_info_1) {
603 		ghcb_set_rax(ghcb, regs->ax);
604 		ghcb_set_rdx(ghcb, regs->dx);
605 	}
606 
607 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, exit_info_1, 0);
608 
609 	if ((ret == ES_OK) && (!exit_info_1)) {
610 		regs->ax = ghcb->save.rax;
611 		regs->dx = ghcb->save.rdx;
612 	}
613 
614 	return ret;
615 }
616 
617 /*
618  * This function runs on the first #VC exception after the kernel
619  * switched to virtual addresses.
620  */
sev_es_setup_ghcb(void)621 static bool __init sev_es_setup_ghcb(void)
622 {
623 	/* First make sure the hypervisor talks a supported protocol. */
624 	if (!sev_es_negotiate_protocol())
625 		return false;
626 
627 	/*
628 	 * Clear the boot_ghcb. The first exception comes in before the bss
629 	 * section is cleared.
630 	 */
631 	memset(&boot_ghcb_page, 0, PAGE_SIZE);
632 
633 	/* Alright - Make the boot-ghcb public */
634 	boot_ghcb = &boot_ghcb_page;
635 
636 	return true;
637 }
638 
639 #ifdef CONFIG_HOTPLUG_CPU
sev_es_ap_hlt_loop(void)640 static void sev_es_ap_hlt_loop(void)
641 {
642 	struct ghcb_state state;
643 	struct ghcb *ghcb;
644 
645 	ghcb = __sev_get_ghcb(&state);
646 
647 	while (true) {
648 		vc_ghcb_invalidate(ghcb);
649 		ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
650 		ghcb_set_sw_exit_info_1(ghcb, 0);
651 		ghcb_set_sw_exit_info_2(ghcb, 0);
652 
653 		sev_es_wr_ghcb_msr(__pa(ghcb));
654 		VMGEXIT();
655 
656 		/* Wakeup signal? */
657 		if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
658 		    ghcb->save.sw_exit_info_2)
659 			break;
660 	}
661 
662 	__sev_put_ghcb(&state);
663 }
664 
665 /*
666  * Play_dead handler when running under SEV-ES. This is needed because
667  * the hypervisor can't deliver an SIPI request to restart the AP.
668  * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
669  * hypervisor wakes it up again.
670  */
sev_es_play_dead(void)671 static void sev_es_play_dead(void)
672 {
673 	play_dead_common();
674 
675 	/* IRQs now disabled */
676 
677 	sev_es_ap_hlt_loop();
678 
679 	/*
680 	 * If we get here, the VCPU was woken up again. Jump to CPU
681 	 * startup code to get it back online.
682 	 */
683 	start_cpu0();
684 }
685 #else  /* CONFIG_HOTPLUG_CPU */
686 #define sev_es_play_dead	native_play_dead
687 #endif /* CONFIG_HOTPLUG_CPU */
688 
689 #ifdef CONFIG_SMP
sev_es_setup_play_dead(void)690 static void __init sev_es_setup_play_dead(void)
691 {
692 	smp_ops.play_dead = sev_es_play_dead;
693 }
694 #else
sev_es_setup_play_dead(void)695 static inline void sev_es_setup_play_dead(void) { }
696 #endif
697 
alloc_runtime_data(int cpu)698 static void __init alloc_runtime_data(int cpu)
699 {
700 	struct sev_es_runtime_data *data;
701 
702 	data = memblock_alloc(sizeof(*data), PAGE_SIZE);
703 	if (!data)
704 		panic("Can't allocate SEV-ES runtime data");
705 
706 	per_cpu(runtime_data, cpu) = data;
707 }
708 
init_ghcb(int cpu)709 static void __init init_ghcb(int cpu)
710 {
711 	struct sev_es_runtime_data *data;
712 	int err;
713 
714 	data = per_cpu(runtime_data, cpu);
715 
716 	err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
717 					 sizeof(data->ghcb_page));
718 	if (err)
719 		panic("Can't map GHCBs unencrypted");
720 
721 	memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
722 
723 	data->ghcb_active = false;
724 	data->backup_ghcb_active = false;
725 }
726 
sev_es_init_vc_handling(void)727 void __init sev_es_init_vc_handling(void)
728 {
729 	int cpu;
730 
731 	BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
732 
733 	if (!sev_es_active())
734 		return;
735 
736 	if (!sev_es_check_cpu_features())
737 		panic("SEV-ES CPU Features missing");
738 
739 	/* Enable SEV-ES special handling */
740 	static_branch_enable(&sev_es_enable_key);
741 
742 	/* Initialize per-cpu GHCB pages */
743 	for_each_possible_cpu(cpu) {
744 		alloc_runtime_data(cpu);
745 		init_ghcb(cpu);
746 	}
747 
748 	sev_es_setup_play_dead();
749 
750 	/* Secondary CPUs use the runtime #VC handler */
751 	initial_vc_handler = (unsigned long)kernel_exc_vmm_communication;
752 }
753 
vc_early_forward_exception(struct es_em_ctxt * ctxt)754 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
755 {
756 	int trapnr = ctxt->fi.vector;
757 
758 	if (trapnr == X86_TRAP_PF)
759 		native_write_cr2(ctxt->fi.cr2);
760 
761 	ctxt->regs->orig_ax = ctxt->fi.error_code;
762 	do_early_exception(ctxt->regs, trapnr);
763 }
764 
vc_insn_get_reg(struct es_em_ctxt * ctxt)765 static long *vc_insn_get_reg(struct es_em_ctxt *ctxt)
766 {
767 	long *reg_array;
768 	int offset;
769 
770 	reg_array = (long *)ctxt->regs;
771 	offset    = insn_get_modrm_reg_off(&ctxt->insn, ctxt->regs);
772 
773 	if (offset < 0)
774 		return NULL;
775 
776 	offset /= sizeof(long);
777 
778 	return reg_array + offset;
779 }
780 
vc_insn_get_rm(struct es_em_ctxt * ctxt)781 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
782 {
783 	long *reg_array;
784 	int offset;
785 
786 	reg_array = (long *)ctxt->regs;
787 	offset    = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
788 
789 	if (offset < 0)
790 		return NULL;
791 
792 	offset /= sizeof(long);
793 
794 	return reg_array + offset;
795 }
vc_do_mmio(struct ghcb * ghcb,struct es_em_ctxt * ctxt,unsigned int bytes,bool read)796 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
797 				 unsigned int bytes, bool read)
798 {
799 	u64 exit_code, exit_info_1, exit_info_2;
800 	unsigned long ghcb_pa = __pa(ghcb);
801 	enum es_result res;
802 	phys_addr_t paddr;
803 	void __user *ref;
804 
805 	ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
806 	if (ref == (void __user *)-1L)
807 		return ES_UNSUPPORTED;
808 
809 	exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
810 
811 	res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
812 	if (res != ES_OK) {
813 		if (res == ES_EXCEPTION && !read)
814 			ctxt->fi.error_code |= X86_PF_WRITE;
815 
816 		return res;
817 	}
818 
819 	exit_info_1 = paddr;
820 	/* Can never be greater than 8 */
821 	exit_info_2 = bytes;
822 
823 	ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
824 
825 	return sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, exit_info_1, exit_info_2);
826 }
827 
vc_handle_mmio_twobyte_ops(struct ghcb * ghcb,struct es_em_ctxt * ctxt)828 static enum es_result vc_handle_mmio_twobyte_ops(struct ghcb *ghcb,
829 						 struct es_em_ctxt *ctxt)
830 {
831 	struct insn *insn = &ctxt->insn;
832 	unsigned int bytes = 0;
833 	enum es_result ret;
834 	int sign_byte;
835 	long *reg_data;
836 
837 	switch (insn->opcode.bytes[1]) {
838 		/* MMIO Read w/ zero-extension */
839 	case 0xb6:
840 		bytes = 1;
841 		fallthrough;
842 	case 0xb7:
843 		if (!bytes)
844 			bytes = 2;
845 
846 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
847 		if (ret)
848 			break;
849 
850 		/* Zero extend based on operand size */
851 		reg_data = vc_insn_get_reg(ctxt);
852 		if (!reg_data)
853 			return ES_DECODE_FAILED;
854 
855 		memset(reg_data, 0, insn->opnd_bytes);
856 
857 		memcpy(reg_data, ghcb->shared_buffer, bytes);
858 		break;
859 
860 		/* MMIO Read w/ sign-extension */
861 	case 0xbe:
862 		bytes = 1;
863 		fallthrough;
864 	case 0xbf:
865 		if (!bytes)
866 			bytes = 2;
867 
868 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
869 		if (ret)
870 			break;
871 
872 		/* Sign extend based on operand size */
873 		reg_data = vc_insn_get_reg(ctxt);
874 		if (!reg_data)
875 			return ES_DECODE_FAILED;
876 
877 		if (bytes == 1) {
878 			u8 *val = (u8 *)ghcb->shared_buffer;
879 
880 			sign_byte = (*val & 0x80) ? 0xff : 0x00;
881 		} else {
882 			u16 *val = (u16 *)ghcb->shared_buffer;
883 
884 			sign_byte = (*val & 0x8000) ? 0xff : 0x00;
885 		}
886 		memset(reg_data, sign_byte, insn->opnd_bytes);
887 
888 		memcpy(reg_data, ghcb->shared_buffer, bytes);
889 		break;
890 
891 	default:
892 		ret = ES_UNSUPPORTED;
893 	}
894 
895 	return ret;
896 }
897 
898 /*
899  * The MOVS instruction has two memory operands, which raises the
900  * problem that it is not known whether the access to the source or the
901  * destination caused the #VC exception (and hence whether an MMIO read
902  * or write operation needs to be emulated).
903  *
904  * Instead of playing games with walking page-tables and trying to guess
905  * whether the source or destination is an MMIO range, split the move
906  * into two operations, a read and a write with only one memory operand.
907  * This will cause a nested #VC exception on the MMIO address which can
908  * then be handled.
909  *
910  * This implementation has the benefit that it also supports MOVS where
911  * source _and_ destination are MMIO regions.
912  *
913  * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
914  * rare operation. If it turns out to be a performance problem the split
915  * operations can be moved to memcpy_fromio() and memcpy_toio().
916  */
vc_handle_mmio_movs(struct es_em_ctxt * ctxt,unsigned int bytes)917 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
918 					  unsigned int bytes)
919 {
920 	unsigned long ds_base, es_base;
921 	unsigned char *src, *dst;
922 	unsigned char buffer[8];
923 	enum es_result ret;
924 	bool rep;
925 	int off;
926 
927 	ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
928 	es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
929 
930 	if (ds_base == -1L || es_base == -1L) {
931 		ctxt->fi.vector = X86_TRAP_GP;
932 		ctxt->fi.error_code = 0;
933 		return ES_EXCEPTION;
934 	}
935 
936 	src = ds_base + (unsigned char *)ctxt->regs->si;
937 	dst = es_base + (unsigned char *)ctxt->regs->di;
938 
939 	ret = vc_read_mem(ctxt, src, buffer, bytes);
940 	if (ret != ES_OK)
941 		return ret;
942 
943 	ret = vc_write_mem(ctxt, dst, buffer, bytes);
944 	if (ret != ES_OK)
945 		return ret;
946 
947 	if (ctxt->regs->flags & X86_EFLAGS_DF)
948 		off = -bytes;
949 	else
950 		off =  bytes;
951 
952 	ctxt->regs->si += off;
953 	ctxt->regs->di += off;
954 
955 	rep = insn_has_rep_prefix(&ctxt->insn);
956 	if (rep)
957 		ctxt->regs->cx -= 1;
958 
959 	if (!rep || ctxt->regs->cx == 0)
960 		return ES_OK;
961 	else
962 		return ES_RETRY;
963 }
964 
vc_handle_mmio(struct ghcb * ghcb,struct es_em_ctxt * ctxt)965 static enum es_result vc_handle_mmio(struct ghcb *ghcb,
966 				     struct es_em_ctxt *ctxt)
967 {
968 	struct insn *insn = &ctxt->insn;
969 	unsigned int bytes = 0;
970 	enum es_result ret;
971 	long *reg_data;
972 
973 	switch (insn->opcode.bytes[0]) {
974 	/* MMIO Write */
975 	case 0x88:
976 		bytes = 1;
977 		fallthrough;
978 	case 0x89:
979 		if (!bytes)
980 			bytes = insn->opnd_bytes;
981 
982 		reg_data = vc_insn_get_reg(ctxt);
983 		if (!reg_data)
984 			return ES_DECODE_FAILED;
985 
986 		memcpy(ghcb->shared_buffer, reg_data, bytes);
987 
988 		ret = vc_do_mmio(ghcb, ctxt, bytes, false);
989 		break;
990 
991 	case 0xc6:
992 		bytes = 1;
993 		fallthrough;
994 	case 0xc7:
995 		if (!bytes)
996 			bytes = insn->opnd_bytes;
997 
998 		memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
999 
1000 		ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1001 		break;
1002 
1003 		/* MMIO Read */
1004 	case 0x8a:
1005 		bytes = 1;
1006 		fallthrough;
1007 	case 0x8b:
1008 		if (!bytes)
1009 			bytes = insn->opnd_bytes;
1010 
1011 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1012 		if (ret)
1013 			break;
1014 
1015 		reg_data = vc_insn_get_reg(ctxt);
1016 		if (!reg_data)
1017 			return ES_DECODE_FAILED;
1018 
1019 		/* Zero-extend for 32-bit operation */
1020 		if (bytes == 4)
1021 			*reg_data = 0;
1022 
1023 		memcpy(reg_data, ghcb->shared_buffer, bytes);
1024 		break;
1025 
1026 		/* MOVS instruction */
1027 	case 0xa4:
1028 		bytes = 1;
1029 		fallthrough;
1030 	case 0xa5:
1031 		if (!bytes)
1032 			bytes = insn->opnd_bytes;
1033 
1034 		ret = vc_handle_mmio_movs(ctxt, bytes);
1035 		break;
1036 		/* Two-Byte Opcodes */
1037 	case 0x0f:
1038 		ret = vc_handle_mmio_twobyte_ops(ghcb, ctxt);
1039 		break;
1040 	default:
1041 		ret = ES_UNSUPPORTED;
1042 	}
1043 
1044 	return ret;
1045 }
1046 
vc_handle_dr7_write(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1047 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1048 					  struct es_em_ctxt *ctxt)
1049 {
1050 	struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1051 	long val, *reg = vc_insn_get_rm(ctxt);
1052 	enum es_result ret;
1053 
1054 	if (!reg)
1055 		return ES_DECODE_FAILED;
1056 
1057 	val = *reg;
1058 
1059 	/* Upper 32 bits must be written as zeroes */
1060 	if (val >> 32) {
1061 		ctxt->fi.vector = X86_TRAP_GP;
1062 		ctxt->fi.error_code = 0;
1063 		return ES_EXCEPTION;
1064 	}
1065 
1066 	/* Clear out other reserved bits and set bit 10 */
1067 	val = (val & 0xffff23ffL) | BIT(10);
1068 
1069 	/* Early non-zero writes to DR7 are not supported */
1070 	if (!data && (val & ~DR7_RESET_VALUE))
1071 		return ES_UNSUPPORTED;
1072 
1073 	/* Using a value of 0 for ExitInfo1 means RAX holds the value */
1074 	ghcb_set_rax(ghcb, val);
1075 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1076 	if (ret != ES_OK)
1077 		return ret;
1078 
1079 	if (data)
1080 		data->dr7 = val;
1081 
1082 	return ES_OK;
1083 }
1084 
vc_handle_dr7_read(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1085 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1086 					 struct es_em_ctxt *ctxt)
1087 {
1088 	struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1089 	long *reg = vc_insn_get_rm(ctxt);
1090 
1091 	if (!reg)
1092 		return ES_DECODE_FAILED;
1093 
1094 	if (data)
1095 		*reg = data->dr7;
1096 	else
1097 		*reg = DR7_RESET_VALUE;
1098 
1099 	return ES_OK;
1100 }
1101 
vc_handle_wbinvd(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1102 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1103 				       struct es_em_ctxt *ctxt)
1104 {
1105 	return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
1106 }
1107 
vc_handle_rdpmc(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1108 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1109 {
1110 	enum es_result ret;
1111 
1112 	ghcb_set_rcx(ghcb, ctxt->regs->cx);
1113 
1114 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
1115 	if (ret != ES_OK)
1116 		return ret;
1117 
1118 	if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1119 		return ES_VMM_ERROR;
1120 
1121 	ctxt->regs->ax = ghcb->save.rax;
1122 	ctxt->regs->dx = ghcb->save.rdx;
1123 
1124 	return ES_OK;
1125 }
1126 
vc_handle_monitor(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1127 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1128 					struct es_em_ctxt *ctxt)
1129 {
1130 	/*
1131 	 * Treat it as a NOP and do not leak a physical address to the
1132 	 * hypervisor.
1133 	 */
1134 	return ES_OK;
1135 }
1136 
vc_handle_mwait(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1137 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1138 				      struct es_em_ctxt *ctxt)
1139 {
1140 	/* Treat the same as MONITOR/MONITORX */
1141 	return ES_OK;
1142 }
1143 
vc_handle_vmmcall(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1144 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1145 					struct es_em_ctxt *ctxt)
1146 {
1147 	enum es_result ret;
1148 
1149 	ghcb_set_rax(ghcb, ctxt->regs->ax);
1150 	ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1151 
1152 	if (x86_platform.hyper.sev_es_hcall_prepare)
1153 		x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1154 
1155 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1156 	if (ret != ES_OK)
1157 		return ret;
1158 
1159 	if (!ghcb_rax_is_valid(ghcb))
1160 		return ES_VMM_ERROR;
1161 
1162 	ctxt->regs->ax = ghcb->save.rax;
1163 
1164 	/*
1165 	 * Call sev_es_hcall_finish() after regs->ax is already set.
1166 	 * This allows the hypervisor handler to overwrite it again if
1167 	 * necessary.
1168 	 */
1169 	if (x86_platform.hyper.sev_es_hcall_finish &&
1170 	    !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1171 		return ES_VMM_ERROR;
1172 
1173 	return ES_OK;
1174 }
1175 
vc_handle_trap_ac(struct ghcb * ghcb,struct es_em_ctxt * ctxt)1176 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1177 					struct es_em_ctxt *ctxt)
1178 {
1179 	/*
1180 	 * Calling ecx_alignment_check() directly does not work, because it
1181 	 * enables IRQs and the GHCB is active. Forward the exception and call
1182 	 * it later from vc_forward_exception().
1183 	 */
1184 	ctxt->fi.vector = X86_TRAP_AC;
1185 	ctxt->fi.error_code = 0;
1186 	return ES_EXCEPTION;
1187 }
1188 
vc_handle_exitcode(struct es_em_ctxt * ctxt,struct ghcb * ghcb,unsigned long exit_code)1189 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1190 					 struct ghcb *ghcb,
1191 					 unsigned long exit_code)
1192 {
1193 	enum es_result result;
1194 
1195 	switch (exit_code) {
1196 	case SVM_EXIT_READ_DR7:
1197 		result = vc_handle_dr7_read(ghcb, ctxt);
1198 		break;
1199 	case SVM_EXIT_WRITE_DR7:
1200 		result = vc_handle_dr7_write(ghcb, ctxt);
1201 		break;
1202 	case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1203 		result = vc_handle_trap_ac(ghcb, ctxt);
1204 		break;
1205 	case SVM_EXIT_RDTSC:
1206 	case SVM_EXIT_RDTSCP:
1207 		result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1208 		break;
1209 	case SVM_EXIT_RDPMC:
1210 		result = vc_handle_rdpmc(ghcb, ctxt);
1211 		break;
1212 	case SVM_EXIT_INVD:
1213 		pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1214 		result = ES_UNSUPPORTED;
1215 		break;
1216 	case SVM_EXIT_CPUID:
1217 		result = vc_handle_cpuid(ghcb, ctxt);
1218 		break;
1219 	case SVM_EXIT_IOIO:
1220 		result = vc_handle_ioio(ghcb, ctxt);
1221 		break;
1222 	case SVM_EXIT_MSR:
1223 		result = vc_handle_msr(ghcb, ctxt);
1224 		break;
1225 	case SVM_EXIT_VMMCALL:
1226 		result = vc_handle_vmmcall(ghcb, ctxt);
1227 		break;
1228 	case SVM_EXIT_WBINVD:
1229 		result = vc_handle_wbinvd(ghcb, ctxt);
1230 		break;
1231 	case SVM_EXIT_MONITOR:
1232 		result = vc_handle_monitor(ghcb, ctxt);
1233 		break;
1234 	case SVM_EXIT_MWAIT:
1235 		result = vc_handle_mwait(ghcb, ctxt);
1236 		break;
1237 	case SVM_EXIT_NPF:
1238 		result = vc_handle_mmio(ghcb, ctxt);
1239 		break;
1240 	default:
1241 		/*
1242 		 * Unexpected #VC exception
1243 		 */
1244 		result = ES_UNSUPPORTED;
1245 	}
1246 
1247 	return result;
1248 }
1249 
vc_forward_exception(struct es_em_ctxt * ctxt)1250 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1251 {
1252 	long error_code = ctxt->fi.error_code;
1253 	int trapnr = ctxt->fi.vector;
1254 
1255 	ctxt->regs->orig_ax = ctxt->fi.error_code;
1256 
1257 	switch (trapnr) {
1258 	case X86_TRAP_GP:
1259 		exc_general_protection(ctxt->regs, error_code);
1260 		break;
1261 	case X86_TRAP_UD:
1262 		exc_invalid_op(ctxt->regs);
1263 		break;
1264 	case X86_TRAP_PF:
1265 		write_cr2(ctxt->fi.cr2);
1266 		exc_page_fault(ctxt->regs, error_code);
1267 		break;
1268 	case X86_TRAP_AC:
1269 		exc_alignment_check(ctxt->regs, error_code);
1270 		break;
1271 	default:
1272 		pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1273 		BUG();
1274 	}
1275 }
1276 
on_vc_fallback_stack(struct pt_regs * regs)1277 static __always_inline bool on_vc_fallback_stack(struct pt_regs *regs)
1278 {
1279 	unsigned long sp = (unsigned long)regs;
1280 
1281 	return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1282 }
1283 
vc_raw_handle_exception(struct pt_regs * regs,unsigned long error_code)1284 static bool vc_raw_handle_exception(struct pt_regs *regs, unsigned long error_code)
1285 {
1286 	struct ghcb_state state;
1287 	struct es_em_ctxt ctxt;
1288 	enum es_result result;
1289 	struct ghcb *ghcb;
1290 	bool ret = true;
1291 
1292 	ghcb = __sev_get_ghcb(&state);
1293 
1294 	vc_ghcb_invalidate(ghcb);
1295 	result = vc_init_em_ctxt(&ctxt, regs, error_code);
1296 
1297 	if (result == ES_OK)
1298 		result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1299 
1300 	__sev_put_ghcb(&state);
1301 
1302 	/* Done - now check the result */
1303 	switch (result) {
1304 	case ES_OK:
1305 		vc_finish_insn(&ctxt);
1306 		break;
1307 	case ES_UNSUPPORTED:
1308 		pr_err_ratelimited("Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1309 				   error_code, regs->ip);
1310 		ret = false;
1311 		break;
1312 	case ES_VMM_ERROR:
1313 		pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1314 				   error_code, regs->ip);
1315 		ret = false;
1316 		break;
1317 	case ES_DECODE_FAILED:
1318 		pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1319 				   error_code, regs->ip);
1320 		ret = false;
1321 		break;
1322 	case ES_EXCEPTION:
1323 		vc_forward_exception(&ctxt);
1324 		break;
1325 	case ES_RETRY:
1326 		/* Nothing to do */
1327 		break;
1328 	default:
1329 		pr_emerg("Unknown result in %s():%d\n", __func__, result);
1330 		/*
1331 		 * Emulating the instruction which caused the #VC exception
1332 		 * failed - can't continue so print debug information
1333 		 */
1334 		BUG();
1335 	}
1336 
1337 	return ret;
1338 }
1339 
vc_is_db(unsigned long error_code)1340 static __always_inline bool vc_is_db(unsigned long error_code)
1341 {
1342 	return error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB;
1343 }
1344 
1345 /*
1346  * Runtime #VC exception handler when raised from kernel mode. Runs in NMI mode
1347  * and will panic when an error happens.
1348  */
DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)1349 DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)
1350 {
1351 	irqentry_state_t irq_state;
1352 
1353 	/*
1354 	 * With the current implementation it is always possible to switch to a
1355 	 * safe stack because #VC exceptions only happen at known places, like
1356 	 * intercepted instructions or accesses to MMIO areas/IO ports. They can
1357 	 * also happen with code instrumentation when the hypervisor intercepts
1358 	 * #DB, but the critical paths are forbidden to be instrumented, so #DB
1359 	 * exceptions currently also only happen in safe places.
1360 	 *
1361 	 * But keep this here in case the noinstr annotations are violated due
1362 	 * to bug elsewhere.
1363 	 */
1364 	if (unlikely(on_vc_fallback_stack(regs))) {
1365 		instrumentation_begin();
1366 		panic("Can't handle #VC exception from unsupported context\n");
1367 		instrumentation_end();
1368 	}
1369 
1370 	/*
1371 	 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1372 	 */
1373 	if (vc_is_db(error_code)) {
1374 		exc_debug(regs);
1375 		return;
1376 	}
1377 
1378 	irq_state = irqentry_nmi_enter(regs);
1379 
1380 	instrumentation_begin();
1381 
1382 	if (!vc_raw_handle_exception(regs, error_code)) {
1383 		/* Show some debug info */
1384 		show_regs(regs);
1385 
1386 		/* Ask hypervisor to sev_es_terminate */
1387 		sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1388 
1389 		/* If that fails and we get here - just panic */
1390 		panic("Returned from Terminate-Request to Hypervisor\n");
1391 	}
1392 
1393 	instrumentation_end();
1394 	irqentry_nmi_exit(regs, irq_state);
1395 }
1396 
1397 /*
1398  * Runtime #VC exception handler when raised from user mode. Runs in IRQ mode
1399  * and will kill the current task with SIGBUS when an error happens.
1400  */
DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)1401 DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)
1402 {
1403 	/*
1404 	 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1405 	 */
1406 	if (vc_is_db(error_code)) {
1407 		noist_exc_debug(regs);
1408 		return;
1409 	}
1410 
1411 	irqentry_enter_from_user_mode(regs);
1412 	instrumentation_begin();
1413 
1414 	if (!vc_raw_handle_exception(regs, error_code)) {
1415 		/*
1416 		 * Do not kill the machine if user-space triggered the
1417 		 * exception. Send SIGBUS instead and let user-space deal with
1418 		 * it.
1419 		 */
1420 		force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1421 	}
1422 
1423 	instrumentation_end();
1424 	irqentry_exit_to_user_mode(regs);
1425 }
1426 
handle_vc_boot_ghcb(struct pt_regs * regs)1427 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1428 {
1429 	unsigned long exit_code = regs->orig_ax;
1430 	struct es_em_ctxt ctxt;
1431 	enum es_result result;
1432 
1433 	/* Do initial setup or terminate the guest */
1434 	if (unlikely(boot_ghcb == NULL && !sev_es_setup_ghcb()))
1435 		sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1436 
1437 	vc_ghcb_invalidate(boot_ghcb);
1438 
1439 	result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1440 	if (result == ES_OK)
1441 		result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1442 
1443 	/* Done - now check the result */
1444 	switch (result) {
1445 	case ES_OK:
1446 		vc_finish_insn(&ctxt);
1447 		break;
1448 	case ES_UNSUPPORTED:
1449 		early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1450 				exit_code, regs->ip);
1451 		goto fail;
1452 	case ES_VMM_ERROR:
1453 		early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1454 				exit_code, regs->ip);
1455 		goto fail;
1456 	case ES_DECODE_FAILED:
1457 		early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1458 				exit_code, regs->ip);
1459 		goto fail;
1460 	case ES_EXCEPTION:
1461 		vc_early_forward_exception(&ctxt);
1462 		break;
1463 	case ES_RETRY:
1464 		/* Nothing to do */
1465 		break;
1466 	default:
1467 		BUG();
1468 	}
1469 
1470 	return true;
1471 
1472 fail:
1473 	show_regs(regs);
1474 
1475 	while (true)
1476 		halt();
1477 }
1478