xref: /linux/arch/x86/coco/sev/vc-handle.c (revision 260f6f4fda93c8485c8037865c941b42b9cba5d2)
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: " fmt
11 
12 #include <linux/sched/debug.h>	/* For show_regs() */
13 #include <linux/cc_platform.h>
14 #include <linux/printk.h>
15 #include <linux/mm_types.h>
16 #include <linux/kernel.h>
17 #include <linux/mm.h>
18 #include <linux/io.h>
19 #include <linux/psp-sev.h>
20 #include <linux/efi.h>
21 #include <uapi/linux/sev-guest.h>
22 
23 #include <asm/init.h>
24 #include <asm/stacktrace.h>
25 #include <asm/sev.h>
26 #include <asm/sev-internal.h>
27 #include <asm/insn-eval.h>
28 #include <asm/fpu/xcr.h>
29 #include <asm/processor.h>
30 #include <asm/setup.h>
31 #include <asm/traps.h>
32 #include <asm/svm.h>
33 #include <asm/smp.h>
34 #include <asm/cpu.h>
35 #include <asm/apic.h>
36 #include <asm/cpuid/api.h>
37 
38 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
39 					   unsigned long vaddr, phys_addr_t *paddr)
40 {
41 	unsigned long va = (unsigned long)vaddr;
42 	unsigned int level;
43 	phys_addr_t pa;
44 	pgd_t *pgd;
45 	pte_t *pte;
46 
47 	pgd = __va(read_cr3_pa());
48 	pgd = &pgd[pgd_index(va)];
49 	pte = lookup_address_in_pgd(pgd, va, &level);
50 	if (!pte) {
51 		ctxt->fi.vector     = X86_TRAP_PF;
52 		ctxt->fi.cr2        = vaddr;
53 		ctxt->fi.error_code = 0;
54 
55 		if (user_mode(ctxt->regs))
56 			ctxt->fi.error_code |= X86_PF_USER;
57 
58 		return ES_EXCEPTION;
59 	}
60 
61 	if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
62 		/* Emulated MMIO to/from encrypted memory not supported */
63 		return ES_UNSUPPORTED;
64 
65 	pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
66 	pa |= va & ~page_level_mask(level);
67 
68 	*paddr = pa;
69 
70 	return ES_OK;
71 }
72 
73 static enum es_result vc_ioio_check(struct es_em_ctxt *ctxt, u16 port, size_t size)
74 {
75 	BUG_ON(size > 4);
76 
77 	if (user_mode(ctxt->regs)) {
78 		struct thread_struct *t = &current->thread;
79 		struct io_bitmap *iobm = t->io_bitmap;
80 		size_t idx;
81 
82 		if (!iobm)
83 			goto fault;
84 
85 		for (idx = port; idx < port + size; ++idx) {
86 			if (test_bit(idx, iobm->bitmap))
87 				goto fault;
88 		}
89 	}
90 
91 	return ES_OK;
92 
93 fault:
94 	ctxt->fi.vector = X86_TRAP_GP;
95 	ctxt->fi.error_code = 0;
96 
97 	return ES_EXCEPTION;
98 }
99 
100 void vc_forward_exception(struct es_em_ctxt *ctxt)
101 {
102 	long error_code = ctxt->fi.error_code;
103 	int trapnr = ctxt->fi.vector;
104 
105 	ctxt->regs->orig_ax = ctxt->fi.error_code;
106 
107 	switch (trapnr) {
108 	case X86_TRAP_GP:
109 		exc_general_protection(ctxt->regs, error_code);
110 		break;
111 	case X86_TRAP_UD:
112 		exc_invalid_op(ctxt->regs);
113 		break;
114 	case X86_TRAP_PF:
115 		write_cr2(ctxt->fi.cr2);
116 		exc_page_fault(ctxt->regs, error_code);
117 		break;
118 	case X86_TRAP_AC:
119 		exc_alignment_check(ctxt->regs, error_code);
120 		break;
121 	default:
122 		pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
123 		BUG();
124 	}
125 }
126 
127 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
128 				unsigned char *buffer)
129 {
130 	return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
131 }
132 
133 static enum es_result __vc_decode_user_insn(struct es_em_ctxt *ctxt)
134 {
135 	char buffer[MAX_INSN_SIZE];
136 	int insn_bytes;
137 
138 	insn_bytes = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
139 	if (insn_bytes == 0) {
140 		/* Nothing could be copied */
141 		ctxt->fi.vector     = X86_TRAP_PF;
142 		ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
143 		ctxt->fi.cr2        = ctxt->regs->ip;
144 		return ES_EXCEPTION;
145 	} else if (insn_bytes == -EINVAL) {
146 		/* Effective RIP could not be calculated */
147 		ctxt->fi.vector     = X86_TRAP_GP;
148 		ctxt->fi.error_code = 0;
149 		ctxt->fi.cr2        = 0;
150 		return ES_EXCEPTION;
151 	}
152 
153 	if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, insn_bytes))
154 		return ES_DECODE_FAILED;
155 
156 	if (ctxt->insn.immediate.got)
157 		return ES_OK;
158 	else
159 		return ES_DECODE_FAILED;
160 }
161 
162 static enum es_result __vc_decode_kern_insn(struct es_em_ctxt *ctxt)
163 {
164 	char buffer[MAX_INSN_SIZE];
165 	int res, ret;
166 
167 	res = vc_fetch_insn_kernel(ctxt, buffer);
168 	if (res) {
169 		ctxt->fi.vector     = X86_TRAP_PF;
170 		ctxt->fi.error_code = X86_PF_INSTR;
171 		ctxt->fi.cr2        = ctxt->regs->ip;
172 		return ES_EXCEPTION;
173 	}
174 
175 	ret = insn_decode(&ctxt->insn, buffer, MAX_INSN_SIZE, INSN_MODE_64);
176 	if (ret < 0)
177 		return ES_DECODE_FAILED;
178 	else
179 		return ES_OK;
180 }
181 
182 /*
183  * User instruction decoding is also required for the EFI runtime. Even though
184  * the EFI runtime is running in kernel mode, it uses special EFI virtual
185  * address mappings that require the use of efi_mm to properly address and
186  * decode.
187  */
188 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
189 {
190 	if (user_mode(ctxt->regs) || mm_is_efi(current->active_mm))
191 		return __vc_decode_user_insn(ctxt);
192 	else
193 		return __vc_decode_kern_insn(ctxt);
194 }
195 
196 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
197 				   char *dst, char *buf, size_t size)
198 {
199 	unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
200 
201 	/*
202 	 * This function uses __put_user() independent of whether kernel or user
203 	 * memory is accessed. This works fine because __put_user() does no
204 	 * sanity checks of the pointer being accessed. All that it does is
205 	 * to report when the access failed.
206 	 *
207 	 * Also, this function runs in atomic context, so __put_user() is not
208 	 * allowed to sleep. The page-fault handler detects that it is running
209 	 * in atomic context and will not try to take mmap_sem and handle the
210 	 * fault, so additional pagefault_enable()/disable() calls are not
211 	 * needed.
212 	 *
213 	 * The access can't be done via copy_to_user() here because
214 	 * vc_write_mem() must not use string instructions to access unsafe
215 	 * memory. The reason is that MOVS is emulated by the #VC handler by
216 	 * splitting the move up into a read and a write and taking a nested #VC
217 	 * exception on whatever of them is the MMIO access. Using string
218 	 * instructions here would cause infinite nesting.
219 	 */
220 	switch (size) {
221 	case 1: {
222 		u8 d1;
223 		u8 __user *target = (u8 __user *)dst;
224 
225 		memcpy(&d1, buf, 1);
226 		if (__put_user(d1, target))
227 			goto fault;
228 		break;
229 	}
230 	case 2: {
231 		u16 d2;
232 		u16 __user *target = (u16 __user *)dst;
233 
234 		memcpy(&d2, buf, 2);
235 		if (__put_user(d2, target))
236 			goto fault;
237 		break;
238 	}
239 	case 4: {
240 		u32 d4;
241 		u32 __user *target = (u32 __user *)dst;
242 
243 		memcpy(&d4, buf, 4);
244 		if (__put_user(d4, target))
245 			goto fault;
246 		break;
247 	}
248 	case 8: {
249 		u64 d8;
250 		u64 __user *target = (u64 __user *)dst;
251 
252 		memcpy(&d8, buf, 8);
253 		if (__put_user(d8, target))
254 			goto fault;
255 		break;
256 	}
257 	default:
258 		WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
259 		return ES_UNSUPPORTED;
260 	}
261 
262 	return ES_OK;
263 
264 fault:
265 	if (user_mode(ctxt->regs))
266 		error_code |= X86_PF_USER;
267 
268 	ctxt->fi.vector = X86_TRAP_PF;
269 	ctxt->fi.error_code = error_code;
270 	ctxt->fi.cr2 = (unsigned long)dst;
271 
272 	return ES_EXCEPTION;
273 }
274 
275 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
276 				  char *src, char *buf, size_t size)
277 {
278 	unsigned long error_code = X86_PF_PROT;
279 
280 	/*
281 	 * This function uses __get_user() independent of whether kernel or user
282 	 * memory is accessed. This works fine because __get_user() does no
283 	 * sanity checks of the pointer being accessed. All that it does is
284 	 * to report when the access failed.
285 	 *
286 	 * Also, this function runs in atomic context, so __get_user() is not
287 	 * allowed to sleep. The page-fault handler detects that it is running
288 	 * in atomic context and will not try to take mmap_sem and handle the
289 	 * fault, so additional pagefault_enable()/disable() calls are not
290 	 * needed.
291 	 *
292 	 * The access can't be done via copy_from_user() here because
293 	 * vc_read_mem() must not use string instructions to access unsafe
294 	 * memory. The reason is that MOVS is emulated by the #VC handler by
295 	 * splitting the move up into a read and a write and taking a nested #VC
296 	 * exception on whatever of them is the MMIO access. Using string
297 	 * instructions here would cause infinite nesting.
298 	 */
299 	switch (size) {
300 	case 1: {
301 		u8 d1;
302 		u8 __user *s = (u8 __user *)src;
303 
304 		if (__get_user(d1, s))
305 			goto fault;
306 		memcpy(buf, &d1, 1);
307 		break;
308 	}
309 	case 2: {
310 		u16 d2;
311 		u16 __user *s = (u16 __user *)src;
312 
313 		if (__get_user(d2, s))
314 			goto fault;
315 		memcpy(buf, &d2, 2);
316 		break;
317 	}
318 	case 4: {
319 		u32 d4;
320 		u32 __user *s = (u32 __user *)src;
321 
322 		if (__get_user(d4, s))
323 			goto fault;
324 		memcpy(buf, &d4, 4);
325 		break;
326 	}
327 	case 8: {
328 		u64 d8;
329 		u64 __user *s = (u64 __user *)src;
330 		if (__get_user(d8, s))
331 			goto fault;
332 		memcpy(buf, &d8, 8);
333 		break;
334 	}
335 	default:
336 		WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
337 		return ES_UNSUPPORTED;
338 	}
339 
340 	return ES_OK;
341 
342 fault:
343 	if (user_mode(ctxt->regs))
344 		error_code |= X86_PF_USER;
345 
346 	ctxt->fi.vector = X86_TRAP_PF;
347 	ctxt->fi.error_code = error_code;
348 	ctxt->fi.cr2 = (unsigned long)src;
349 
350 	return ES_EXCEPTION;
351 }
352 
353 #define sev_printk(fmt, ...)		printk(fmt, ##__VA_ARGS__)
354 
355 #include "vc-shared.c"
356 
357 /* Writes to the SVSM CAA MSR are ignored */
358 static enum es_result __vc_handle_msr_caa(struct pt_regs *regs, bool write)
359 {
360 	if (write)
361 		return ES_OK;
362 
363 	regs->ax = lower_32_bits(this_cpu_read(svsm_caa_pa));
364 	regs->dx = upper_32_bits(this_cpu_read(svsm_caa_pa));
365 
366 	return ES_OK;
367 }
368 
369 /*
370  * TSC related accesses should not exit to the hypervisor when a guest is
371  * executing with Secure TSC enabled, so special handling is required for
372  * accesses of MSR_IA32_TSC and MSR_AMD64_GUEST_TSC_FREQ.
373  */
374 static enum es_result __vc_handle_secure_tsc_msrs(struct pt_regs *regs, bool write)
375 {
376 	u64 tsc;
377 
378 	/*
379 	 * GUEST_TSC_FREQ should not be intercepted when Secure TSC is enabled.
380 	 * Terminate the SNP guest when the interception is enabled.
381 	 */
382 	if (regs->cx == MSR_AMD64_GUEST_TSC_FREQ)
383 		return ES_VMM_ERROR;
384 
385 	/*
386 	 * Writes: Writing to MSR_IA32_TSC can cause subsequent reads of the TSC
387 	 *         to return undefined values, so ignore all writes.
388 	 *
389 	 * Reads: Reads of MSR_IA32_TSC should return the current TSC value, use
390 	 *        the value returned by rdtsc_ordered().
391 	 */
392 	if (write) {
393 		WARN_ONCE(1, "TSC MSR writes are verboten!\n");
394 		return ES_OK;
395 	}
396 
397 	tsc = rdtsc_ordered();
398 	regs->ax = lower_32_bits(tsc);
399 	regs->dx = upper_32_bits(tsc);
400 
401 	return ES_OK;
402 }
403 
404 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
405 {
406 	struct pt_regs *regs = ctxt->regs;
407 	enum es_result ret;
408 	bool write;
409 
410 	/* Is it a WRMSR? */
411 	write = ctxt->insn.opcode.bytes[1] == 0x30;
412 
413 	switch (regs->cx) {
414 	case MSR_SVSM_CAA:
415 		return __vc_handle_msr_caa(regs, write);
416 	case MSR_IA32_TSC:
417 	case MSR_AMD64_GUEST_TSC_FREQ:
418 		if (sev_status & MSR_AMD64_SNP_SECURE_TSC)
419 			return __vc_handle_secure_tsc_msrs(regs, write);
420 		break;
421 	default:
422 		break;
423 	}
424 
425 	ghcb_set_rcx(ghcb, regs->cx);
426 	if (write) {
427 		ghcb_set_rax(ghcb, regs->ax);
428 		ghcb_set_rdx(ghcb, regs->dx);
429 	}
430 
431 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, write, 0);
432 
433 	if ((ret == ES_OK) && !write) {
434 		regs->ax = ghcb->save.rax;
435 		regs->dx = ghcb->save.rdx;
436 	}
437 
438 	return ret;
439 }
440 
441 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
442 {
443 	int trapnr = ctxt->fi.vector;
444 
445 	if (trapnr == X86_TRAP_PF)
446 		native_write_cr2(ctxt->fi.cr2);
447 
448 	ctxt->regs->orig_ax = ctxt->fi.error_code;
449 	do_early_exception(ctxt->regs, trapnr);
450 }
451 
452 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
453 {
454 	long *reg_array;
455 	int offset;
456 
457 	reg_array = (long *)ctxt->regs;
458 	offset    = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
459 
460 	if (offset < 0)
461 		return NULL;
462 
463 	offset /= sizeof(long);
464 
465 	return reg_array + offset;
466 }
467 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
468 				 unsigned int bytes, bool read)
469 {
470 	u64 exit_code, exit_info_1, exit_info_2;
471 	unsigned long ghcb_pa = __pa(ghcb);
472 	enum es_result res;
473 	phys_addr_t paddr;
474 	void __user *ref;
475 
476 	ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
477 	if (ref == (void __user *)-1L)
478 		return ES_UNSUPPORTED;
479 
480 	exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
481 
482 	res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
483 	if (res != ES_OK) {
484 		if (res == ES_EXCEPTION && !read)
485 			ctxt->fi.error_code |= X86_PF_WRITE;
486 
487 		return res;
488 	}
489 
490 	exit_info_1 = paddr;
491 	/* Can never be greater than 8 */
492 	exit_info_2 = bytes;
493 
494 	ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
495 
496 	return sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, exit_info_1, exit_info_2);
497 }
498 
499 /*
500  * The MOVS instruction has two memory operands, which raises the
501  * problem that it is not known whether the access to the source or the
502  * destination caused the #VC exception (and hence whether an MMIO read
503  * or write operation needs to be emulated).
504  *
505  * Instead of playing games with walking page-tables and trying to guess
506  * whether the source or destination is an MMIO range, split the move
507  * into two operations, a read and a write with only one memory operand.
508  * This will cause a nested #VC exception on the MMIO address which can
509  * then be handled.
510  *
511  * This implementation has the benefit that it also supports MOVS where
512  * source _and_ destination are MMIO regions.
513  *
514  * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
515  * rare operation. If it turns out to be a performance problem the split
516  * operations can be moved to memcpy_fromio() and memcpy_toio().
517  */
518 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
519 					  unsigned int bytes)
520 {
521 	unsigned long ds_base, es_base;
522 	unsigned char *src, *dst;
523 	unsigned char buffer[8];
524 	enum es_result ret;
525 	bool rep;
526 	int off;
527 
528 	ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
529 	es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
530 
531 	if (ds_base == -1L || es_base == -1L) {
532 		ctxt->fi.vector = X86_TRAP_GP;
533 		ctxt->fi.error_code = 0;
534 		return ES_EXCEPTION;
535 	}
536 
537 	src = ds_base + (unsigned char *)ctxt->regs->si;
538 	dst = es_base + (unsigned char *)ctxt->regs->di;
539 
540 	ret = vc_read_mem(ctxt, src, buffer, bytes);
541 	if (ret != ES_OK)
542 		return ret;
543 
544 	ret = vc_write_mem(ctxt, dst, buffer, bytes);
545 	if (ret != ES_OK)
546 		return ret;
547 
548 	if (ctxt->regs->flags & X86_EFLAGS_DF)
549 		off = -bytes;
550 	else
551 		off =  bytes;
552 
553 	ctxt->regs->si += off;
554 	ctxt->regs->di += off;
555 
556 	rep = insn_has_rep_prefix(&ctxt->insn);
557 	if (rep)
558 		ctxt->regs->cx -= 1;
559 
560 	if (!rep || ctxt->regs->cx == 0)
561 		return ES_OK;
562 	else
563 		return ES_RETRY;
564 }
565 
566 static enum es_result vc_handle_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
567 {
568 	struct insn *insn = &ctxt->insn;
569 	enum insn_mmio_type mmio;
570 	unsigned int bytes = 0;
571 	enum es_result ret;
572 	u8 sign_byte;
573 	long *reg_data;
574 
575 	mmio = insn_decode_mmio(insn, &bytes);
576 	if (mmio == INSN_MMIO_DECODE_FAILED)
577 		return ES_DECODE_FAILED;
578 
579 	if (mmio != INSN_MMIO_WRITE_IMM && mmio != INSN_MMIO_MOVS) {
580 		reg_data = insn_get_modrm_reg_ptr(insn, ctxt->regs);
581 		if (!reg_data)
582 			return ES_DECODE_FAILED;
583 	}
584 
585 	if (user_mode(ctxt->regs))
586 		return ES_UNSUPPORTED;
587 
588 	switch (mmio) {
589 	case INSN_MMIO_WRITE:
590 		memcpy(ghcb->shared_buffer, reg_data, bytes);
591 		ret = vc_do_mmio(ghcb, ctxt, bytes, false);
592 		break;
593 	case INSN_MMIO_WRITE_IMM:
594 		memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
595 		ret = vc_do_mmio(ghcb, ctxt, bytes, false);
596 		break;
597 	case INSN_MMIO_READ:
598 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
599 		if (ret)
600 			break;
601 
602 		/* Zero-extend for 32-bit operation */
603 		if (bytes == 4)
604 			*reg_data = 0;
605 
606 		memcpy(reg_data, ghcb->shared_buffer, bytes);
607 		break;
608 	case INSN_MMIO_READ_ZERO_EXTEND:
609 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
610 		if (ret)
611 			break;
612 
613 		/* Zero extend based on operand size */
614 		memset(reg_data, 0, insn->opnd_bytes);
615 		memcpy(reg_data, ghcb->shared_buffer, bytes);
616 		break;
617 	case INSN_MMIO_READ_SIGN_EXTEND:
618 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
619 		if (ret)
620 			break;
621 
622 		if (bytes == 1) {
623 			u8 *val = (u8 *)ghcb->shared_buffer;
624 
625 			sign_byte = (*val & 0x80) ? 0xff : 0x00;
626 		} else {
627 			u16 *val = (u16 *)ghcb->shared_buffer;
628 
629 			sign_byte = (*val & 0x8000) ? 0xff : 0x00;
630 		}
631 
632 		/* Sign extend based on operand size */
633 		memset(reg_data, sign_byte, insn->opnd_bytes);
634 		memcpy(reg_data, ghcb->shared_buffer, bytes);
635 		break;
636 	case INSN_MMIO_MOVS:
637 		ret = vc_handle_mmio_movs(ctxt, bytes);
638 		break;
639 	default:
640 		ret = ES_UNSUPPORTED;
641 		break;
642 	}
643 
644 	return ret;
645 }
646 
647 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
648 					  struct es_em_ctxt *ctxt)
649 {
650 	struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
651 	long val, *reg = vc_insn_get_rm(ctxt);
652 	enum es_result ret;
653 
654 	if (sev_status & MSR_AMD64_SNP_DEBUG_SWAP)
655 		return ES_VMM_ERROR;
656 
657 	if (!reg)
658 		return ES_DECODE_FAILED;
659 
660 	val = *reg;
661 
662 	/* Upper 32 bits must be written as zeroes */
663 	if (val >> 32) {
664 		ctxt->fi.vector = X86_TRAP_GP;
665 		ctxt->fi.error_code = 0;
666 		return ES_EXCEPTION;
667 	}
668 
669 	/* Clear out other reserved bits and set bit 10 */
670 	val = (val & 0xffff23ffL) | BIT(10);
671 
672 	/* Early non-zero writes to DR7 are not supported */
673 	if (!data && (val & ~DR7_RESET_VALUE))
674 		return ES_UNSUPPORTED;
675 
676 	/* Using a value of 0 for ExitInfo1 means RAX holds the value */
677 	ghcb_set_rax(ghcb, val);
678 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
679 	if (ret != ES_OK)
680 		return ret;
681 
682 	if (data)
683 		data->dr7 = val;
684 
685 	return ES_OK;
686 }
687 
688 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
689 					 struct es_em_ctxt *ctxt)
690 {
691 	struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
692 	long *reg = vc_insn_get_rm(ctxt);
693 
694 	if (sev_status & MSR_AMD64_SNP_DEBUG_SWAP)
695 		return ES_VMM_ERROR;
696 
697 	if (!reg)
698 		return ES_DECODE_FAILED;
699 
700 	if (data)
701 		*reg = data->dr7;
702 	else
703 		*reg = DR7_RESET_VALUE;
704 
705 	return ES_OK;
706 }
707 
708 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
709 				       struct es_em_ctxt *ctxt)
710 {
711 	return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
712 }
713 
714 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
715 {
716 	enum es_result ret;
717 
718 	ghcb_set_rcx(ghcb, ctxt->regs->cx);
719 
720 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
721 	if (ret != ES_OK)
722 		return ret;
723 
724 	if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
725 		return ES_VMM_ERROR;
726 
727 	ctxt->regs->ax = ghcb->save.rax;
728 	ctxt->regs->dx = ghcb->save.rdx;
729 
730 	return ES_OK;
731 }
732 
733 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
734 					struct es_em_ctxt *ctxt)
735 {
736 	/*
737 	 * Treat it as a NOP and do not leak a physical address to the
738 	 * hypervisor.
739 	 */
740 	return ES_OK;
741 }
742 
743 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
744 				      struct es_em_ctxt *ctxt)
745 {
746 	/* Treat the same as MONITOR/MONITORX */
747 	return ES_OK;
748 }
749 
750 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
751 					struct es_em_ctxt *ctxt)
752 {
753 	enum es_result ret;
754 
755 	ghcb_set_rax(ghcb, ctxt->regs->ax);
756 	ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
757 
758 	if (x86_platform.hyper.sev_es_hcall_prepare)
759 		x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
760 
761 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
762 	if (ret != ES_OK)
763 		return ret;
764 
765 	if (!ghcb_rax_is_valid(ghcb))
766 		return ES_VMM_ERROR;
767 
768 	ctxt->regs->ax = ghcb->save.rax;
769 
770 	/*
771 	 * Call sev_es_hcall_finish() after regs->ax is already set.
772 	 * This allows the hypervisor handler to overwrite it again if
773 	 * necessary.
774 	 */
775 	if (x86_platform.hyper.sev_es_hcall_finish &&
776 	    !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
777 		return ES_VMM_ERROR;
778 
779 	return ES_OK;
780 }
781 
782 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
783 					struct es_em_ctxt *ctxt)
784 {
785 	/*
786 	 * Calling ecx_alignment_check() directly does not work, because it
787 	 * enables IRQs and the GHCB is active. Forward the exception and call
788 	 * it later from vc_forward_exception().
789 	 */
790 	ctxt->fi.vector = X86_TRAP_AC;
791 	ctxt->fi.error_code = 0;
792 	return ES_EXCEPTION;
793 }
794 
795 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
796 					 struct ghcb *ghcb,
797 					 unsigned long exit_code)
798 {
799 	enum es_result result = vc_check_opcode_bytes(ctxt, exit_code);
800 
801 	if (result != ES_OK)
802 		return result;
803 
804 	switch (exit_code) {
805 	case SVM_EXIT_READ_DR7:
806 		result = vc_handle_dr7_read(ghcb, ctxt);
807 		break;
808 	case SVM_EXIT_WRITE_DR7:
809 		result = vc_handle_dr7_write(ghcb, ctxt);
810 		break;
811 	case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
812 		result = vc_handle_trap_ac(ghcb, ctxt);
813 		break;
814 	case SVM_EXIT_RDTSC:
815 	case SVM_EXIT_RDTSCP:
816 		result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
817 		break;
818 	case SVM_EXIT_RDPMC:
819 		result = vc_handle_rdpmc(ghcb, ctxt);
820 		break;
821 	case SVM_EXIT_INVD:
822 		pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
823 		result = ES_UNSUPPORTED;
824 		break;
825 	case SVM_EXIT_CPUID:
826 		result = vc_handle_cpuid(ghcb, ctxt);
827 		break;
828 	case SVM_EXIT_IOIO:
829 		result = vc_handle_ioio(ghcb, ctxt);
830 		break;
831 	case SVM_EXIT_MSR:
832 		result = vc_handle_msr(ghcb, ctxt);
833 		break;
834 	case SVM_EXIT_VMMCALL:
835 		result = vc_handle_vmmcall(ghcb, ctxt);
836 		break;
837 	case SVM_EXIT_WBINVD:
838 		result = vc_handle_wbinvd(ghcb, ctxt);
839 		break;
840 	case SVM_EXIT_MONITOR:
841 		result = vc_handle_monitor(ghcb, ctxt);
842 		break;
843 	case SVM_EXIT_MWAIT:
844 		result = vc_handle_mwait(ghcb, ctxt);
845 		break;
846 	case SVM_EXIT_NPF:
847 		result = vc_handle_mmio(ghcb, ctxt);
848 		break;
849 	default:
850 		/*
851 		 * Unexpected #VC exception
852 		 */
853 		result = ES_UNSUPPORTED;
854 	}
855 
856 	return result;
857 }
858 
859 static __always_inline bool is_vc2_stack(unsigned long sp)
860 {
861 	return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
862 }
863 
864 static __always_inline bool vc_from_invalid_context(struct pt_regs *regs)
865 {
866 	unsigned long sp, prev_sp;
867 
868 	sp      = (unsigned long)regs;
869 	prev_sp = regs->sp;
870 
871 	/*
872 	 * If the code was already executing on the VC2 stack when the #VC
873 	 * happened, let it proceed to the normal handling routine. This way the
874 	 * code executing on the VC2 stack can cause #VC exceptions to get handled.
875 	 */
876 	return is_vc2_stack(sp) && !is_vc2_stack(prev_sp);
877 }
878 
879 static bool vc_raw_handle_exception(struct pt_regs *regs, unsigned long error_code)
880 {
881 	struct ghcb_state state;
882 	struct es_em_ctxt ctxt;
883 	enum es_result result;
884 	struct ghcb *ghcb;
885 	bool ret = true;
886 
887 	ghcb = __sev_get_ghcb(&state);
888 
889 	vc_ghcb_invalidate(ghcb);
890 	result = vc_init_em_ctxt(&ctxt, regs, error_code);
891 
892 	if (result == ES_OK)
893 		result = vc_handle_exitcode(&ctxt, ghcb, error_code);
894 
895 	__sev_put_ghcb(&state);
896 
897 	/* Done - now check the result */
898 	switch (result) {
899 	case ES_OK:
900 		vc_finish_insn(&ctxt);
901 		break;
902 	case ES_UNSUPPORTED:
903 		pr_err_ratelimited("Unsupported exit-code 0x%02lx in #VC exception (IP: 0x%lx)\n",
904 				   error_code, regs->ip);
905 		ret = false;
906 		break;
907 	case ES_VMM_ERROR:
908 		pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
909 				   error_code, regs->ip);
910 		ret = false;
911 		break;
912 	case ES_DECODE_FAILED:
913 		pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
914 				   error_code, regs->ip);
915 		ret = false;
916 		break;
917 	case ES_EXCEPTION:
918 		vc_forward_exception(&ctxt);
919 		break;
920 	case ES_RETRY:
921 		/* Nothing to do */
922 		break;
923 	default:
924 		pr_emerg("Unknown result in %s():%d\n", __func__, result);
925 		/*
926 		 * Emulating the instruction which caused the #VC exception
927 		 * failed - can't continue so print debug information
928 		 */
929 		BUG();
930 	}
931 
932 	return ret;
933 }
934 
935 static __always_inline bool vc_is_db(unsigned long error_code)
936 {
937 	return error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB;
938 }
939 
940 /*
941  * Runtime #VC exception handler when raised from kernel mode. Runs in NMI mode
942  * and will panic when an error happens.
943  */
944 DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)
945 {
946 	irqentry_state_t irq_state;
947 
948 	/*
949 	 * With the current implementation it is always possible to switch to a
950 	 * safe stack because #VC exceptions only happen at known places, like
951 	 * intercepted instructions or accesses to MMIO areas/IO ports. They can
952 	 * also happen with code instrumentation when the hypervisor intercepts
953 	 * #DB, but the critical paths are forbidden to be instrumented, so #DB
954 	 * exceptions currently also only happen in safe places.
955 	 *
956 	 * But keep this here in case the noinstr annotations are violated due
957 	 * to bug elsewhere.
958 	 */
959 	if (unlikely(vc_from_invalid_context(regs))) {
960 		instrumentation_begin();
961 		panic("Can't handle #VC exception from unsupported context\n");
962 		instrumentation_end();
963 	}
964 
965 	/*
966 	 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
967 	 */
968 	if (vc_is_db(error_code)) {
969 		exc_debug(regs);
970 		return;
971 	}
972 
973 	irq_state = irqentry_nmi_enter(regs);
974 
975 	instrumentation_begin();
976 
977 	if (!vc_raw_handle_exception(regs, error_code)) {
978 		/* Show some debug info */
979 		show_regs(regs);
980 
981 		/* Ask hypervisor to sev_es_terminate */
982 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
983 
984 		/* If that fails and we get here - just panic */
985 		panic("Returned from Terminate-Request to Hypervisor\n");
986 	}
987 
988 	instrumentation_end();
989 	irqentry_nmi_exit(regs, irq_state);
990 }
991 
992 /*
993  * Runtime #VC exception handler when raised from user mode. Runs in IRQ mode
994  * and will kill the current task with SIGBUS when an error happens.
995  */
996 DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)
997 {
998 	/*
999 	 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1000 	 */
1001 	if (vc_is_db(error_code)) {
1002 		noist_exc_debug(regs);
1003 		return;
1004 	}
1005 
1006 	irqentry_enter_from_user_mode(regs);
1007 	instrumentation_begin();
1008 
1009 	if (!vc_raw_handle_exception(regs, error_code)) {
1010 		/*
1011 		 * Do not kill the machine if user-space triggered the
1012 		 * exception. Send SIGBUS instead and let user-space deal with
1013 		 * it.
1014 		 */
1015 		force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1016 	}
1017 
1018 	instrumentation_end();
1019 	irqentry_exit_to_user_mode(regs);
1020 }
1021 
1022 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1023 {
1024 	unsigned long exit_code = regs->orig_ax;
1025 	struct es_em_ctxt ctxt;
1026 	enum es_result result;
1027 
1028 	vc_ghcb_invalidate(boot_ghcb);
1029 
1030 	result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1031 	if (result == ES_OK)
1032 		result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1033 
1034 	/* Done - now check the result */
1035 	switch (result) {
1036 	case ES_OK:
1037 		vc_finish_insn(&ctxt);
1038 		break;
1039 	case ES_UNSUPPORTED:
1040 		early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1041 				exit_code, regs->ip);
1042 		goto fail;
1043 	case ES_VMM_ERROR:
1044 		early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1045 				exit_code, regs->ip);
1046 		goto fail;
1047 	case ES_DECODE_FAILED:
1048 		early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1049 				exit_code, regs->ip);
1050 		goto fail;
1051 	case ES_EXCEPTION:
1052 		vc_early_forward_exception(&ctxt);
1053 		break;
1054 	case ES_RETRY:
1055 		/* Nothing to do */
1056 		break;
1057 	default:
1058 		BUG();
1059 	}
1060 
1061 	return true;
1062 
1063 fail:
1064 	show_regs(regs);
1065 
1066 	sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
1067 }
1068 
1069