xref: /openbmc/linux/arch/x86/kernel/sev.c (revision f77d1a49)
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/percpu-defs.h>
14 #include <linux/cc_platform.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 #include <linux/cpumask.h>
22 #include <linux/efi.h>
23 #include <linux/platform_device.h>
24 #include <linux/io.h>
25 #include <linux/psp-sev.h>
26 #include <uapi/linux/sev-guest.h>
27 
28 #include <asm/cpu_entry_area.h>
29 #include <asm/stacktrace.h>
30 #include <asm/sev.h>
31 #include <asm/insn-eval.h>
32 #include <asm/fpu/xcr.h>
33 #include <asm/processor.h>
34 #include <asm/realmode.h>
35 #include <asm/setup.h>
36 #include <asm/traps.h>
37 #include <asm/svm.h>
38 #include <asm/smp.h>
39 #include <asm/cpu.h>
40 #include <asm/apic.h>
41 #include <asm/cpuid.h>
42 #include <asm/cmdline.h>
43 
44 #define DR7_RESET_VALUE        0x400
45 
46 /* AP INIT values as documented in the APM2  section "Processor Initialization State" */
47 #define AP_INIT_CS_LIMIT		0xffff
48 #define AP_INIT_DS_LIMIT		0xffff
49 #define AP_INIT_LDTR_LIMIT		0xffff
50 #define AP_INIT_GDTR_LIMIT		0xffff
51 #define AP_INIT_IDTR_LIMIT		0xffff
52 #define AP_INIT_TR_LIMIT		0xffff
53 #define AP_INIT_RFLAGS_DEFAULT		0x2
54 #define AP_INIT_DR6_DEFAULT		0xffff0ff0
55 #define AP_INIT_GPAT_DEFAULT		0x0007040600070406ULL
56 #define AP_INIT_XCR0_DEFAULT		0x1
57 #define AP_INIT_X87_FTW_DEFAULT		0x5555
58 #define AP_INIT_X87_FCW_DEFAULT		0x0040
59 #define AP_INIT_CR0_DEFAULT		0x60000010
60 #define AP_INIT_MXCSR_DEFAULT		0x1f80
61 
62 /* For early boot hypervisor communication in SEV-ES enabled guests */
63 static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
64 
65 /*
66  * Needs to be in the .data section because we need it NULL before bss is
67  * cleared
68  */
69 static struct ghcb *boot_ghcb __section(".data");
70 
71 /* Bitmap of SEV features supported by the hypervisor */
72 static u64 sev_hv_features __ro_after_init;
73 
74 /* #VC handler runtime per-CPU data */
75 struct sev_es_runtime_data {
76 	struct ghcb ghcb_page;
77 
78 	/*
79 	 * Reserve one page per CPU as backup storage for the unencrypted GHCB.
80 	 * It is needed when an NMI happens while the #VC handler uses the real
81 	 * GHCB, and the NMI handler itself is causing another #VC exception. In
82 	 * that case the GHCB content of the first handler needs to be backed up
83 	 * and restored.
84 	 */
85 	struct ghcb backup_ghcb;
86 
87 	/*
88 	 * Mark the per-cpu GHCBs as in-use to detect nested #VC exceptions.
89 	 * There is no need for it to be atomic, because nothing is written to
90 	 * the GHCB between the read and the write of ghcb_active. So it is safe
91 	 * to use it when a nested #VC exception happens before the write.
92 	 *
93 	 * This is necessary for example in the #VC->NMI->#VC case when the NMI
94 	 * happens while the first #VC handler uses the GHCB. When the NMI code
95 	 * raises a second #VC handler it might overwrite the contents of the
96 	 * GHCB written by the first handler. To avoid this the content of the
97 	 * GHCB is saved and restored when the GHCB is detected to be in use
98 	 * already.
99 	 */
100 	bool ghcb_active;
101 	bool backup_ghcb_active;
102 
103 	/*
104 	 * Cached DR7 value - write it on DR7 writes and return it on reads.
105 	 * That value will never make it to the real hardware DR7 as debugging
106 	 * is currently unsupported in SEV-ES guests.
107 	 */
108 	unsigned long dr7;
109 };
110 
111 struct ghcb_state {
112 	struct ghcb *ghcb;
113 };
114 
115 static DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
116 static DEFINE_PER_CPU(struct sev_es_save_area *, sev_vmsa);
117 
118 struct sev_config {
119 	__u64 debug		: 1,
120 
121 	      /*
122 	       * A flag used by __set_pages_state() that indicates when the
123 	       * per-CPU GHCB has been created and registered and thus can be
124 	       * used by the BSP instead of the early boot GHCB.
125 	       *
126 	       * For APs, the per-CPU GHCB is created before they are started
127 	       * and registered upon startup, so this flag can be used globally
128 	       * for the BSP and APs.
129 	       */
130 	      ghcbs_initialized	: 1,
131 
132 	      __reserved	: 62;
133 };
134 
135 static struct sev_config sev_cfg __read_mostly;
136 
137 static __always_inline bool on_vc_stack(struct pt_regs *regs)
138 {
139 	unsigned long sp = regs->sp;
140 
141 	/* User-mode RSP is not trusted */
142 	if (user_mode(regs))
143 		return false;
144 
145 	/* SYSCALL gap still has user-mode RSP */
146 	if (ip_within_syscall_gap(regs))
147 		return false;
148 
149 	return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
150 }
151 
152 /*
153  * This function handles the case when an NMI is raised in the #VC
154  * exception handler entry code, before the #VC handler has switched off
155  * its IST stack. In this case, the IST entry for #VC must be adjusted,
156  * so that any nested #VC exception will not overwrite the stack
157  * contents of the interrupted #VC handler.
158  *
159  * The IST entry is adjusted unconditionally so that it can be also be
160  * unconditionally adjusted back in __sev_es_ist_exit(). Otherwise a
161  * nested sev_es_ist_exit() call may adjust back the IST entry too
162  * early.
163  *
164  * The __sev_es_ist_enter() and __sev_es_ist_exit() functions always run
165  * on the NMI IST stack, as they are only called from NMI handling code
166  * right now.
167  */
168 void noinstr __sev_es_ist_enter(struct pt_regs *regs)
169 {
170 	unsigned long old_ist, new_ist;
171 
172 	/* Read old IST entry */
173 	new_ist = old_ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
174 
175 	/*
176 	 * If NMI happened while on the #VC IST stack, set the new IST
177 	 * value below regs->sp, so that the interrupted stack frame is
178 	 * not overwritten by subsequent #VC exceptions.
179 	 */
180 	if (on_vc_stack(regs))
181 		new_ist = regs->sp;
182 
183 	/*
184 	 * Reserve additional 8 bytes and store old IST value so this
185 	 * adjustment can be unrolled in __sev_es_ist_exit().
186 	 */
187 	new_ist -= sizeof(old_ist);
188 	*(unsigned long *)new_ist = old_ist;
189 
190 	/* Set new IST entry */
191 	this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], new_ist);
192 }
193 
194 void noinstr __sev_es_ist_exit(void)
195 {
196 	unsigned long ist;
197 
198 	/* Read IST entry */
199 	ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
200 
201 	if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
202 		return;
203 
204 	/* Read back old IST entry and write it to the TSS */
205 	this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], *(unsigned long *)ist);
206 }
207 
208 /*
209  * Nothing shall interrupt this code path while holding the per-CPU
210  * GHCB. The backup GHCB is only for NMIs interrupting this path.
211  *
212  * Callers must disable local interrupts around it.
213  */
214 static noinstr struct ghcb *__sev_get_ghcb(struct ghcb_state *state)
215 {
216 	struct sev_es_runtime_data *data;
217 	struct ghcb *ghcb;
218 
219 	WARN_ON(!irqs_disabled());
220 
221 	data = this_cpu_read(runtime_data);
222 	ghcb = &data->ghcb_page;
223 
224 	if (unlikely(data->ghcb_active)) {
225 		/* GHCB is already in use - save its contents */
226 
227 		if (unlikely(data->backup_ghcb_active)) {
228 			/*
229 			 * Backup-GHCB is also already in use. There is no way
230 			 * to continue here so just kill the machine. To make
231 			 * panic() work, mark GHCBs inactive so that messages
232 			 * can be printed out.
233 			 */
234 			data->ghcb_active        = false;
235 			data->backup_ghcb_active = false;
236 
237 			instrumentation_begin();
238 			panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
239 			instrumentation_end();
240 		}
241 
242 		/* Mark backup_ghcb active before writing to it */
243 		data->backup_ghcb_active = true;
244 
245 		state->ghcb = &data->backup_ghcb;
246 
247 		/* Backup GHCB content */
248 		*state->ghcb = *ghcb;
249 	} else {
250 		state->ghcb = NULL;
251 		data->ghcb_active = true;
252 	}
253 
254 	return ghcb;
255 }
256 
257 static inline u64 sev_es_rd_ghcb_msr(void)
258 {
259 	return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
260 }
261 
262 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
263 {
264 	u32 low, high;
265 
266 	low  = (u32)(val);
267 	high = (u32)(val >> 32);
268 
269 	native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
270 }
271 
272 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
273 				unsigned char *buffer)
274 {
275 	return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
276 }
277 
278 static enum es_result __vc_decode_user_insn(struct es_em_ctxt *ctxt)
279 {
280 	char buffer[MAX_INSN_SIZE];
281 	int insn_bytes;
282 
283 	insn_bytes = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
284 	if (insn_bytes == 0) {
285 		/* Nothing could be copied */
286 		ctxt->fi.vector     = X86_TRAP_PF;
287 		ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
288 		ctxt->fi.cr2        = ctxt->regs->ip;
289 		return ES_EXCEPTION;
290 	} else if (insn_bytes == -EINVAL) {
291 		/* Effective RIP could not be calculated */
292 		ctxt->fi.vector     = X86_TRAP_GP;
293 		ctxt->fi.error_code = 0;
294 		ctxt->fi.cr2        = 0;
295 		return ES_EXCEPTION;
296 	}
297 
298 	if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, insn_bytes))
299 		return ES_DECODE_FAILED;
300 
301 	if (ctxt->insn.immediate.got)
302 		return ES_OK;
303 	else
304 		return ES_DECODE_FAILED;
305 }
306 
307 static enum es_result __vc_decode_kern_insn(struct es_em_ctxt *ctxt)
308 {
309 	char buffer[MAX_INSN_SIZE];
310 	int res, ret;
311 
312 	res = vc_fetch_insn_kernel(ctxt, buffer);
313 	if (res) {
314 		ctxt->fi.vector     = X86_TRAP_PF;
315 		ctxt->fi.error_code = X86_PF_INSTR;
316 		ctxt->fi.cr2        = ctxt->regs->ip;
317 		return ES_EXCEPTION;
318 	}
319 
320 	ret = insn_decode(&ctxt->insn, buffer, MAX_INSN_SIZE, INSN_MODE_64);
321 	if (ret < 0)
322 		return ES_DECODE_FAILED;
323 	else
324 		return ES_OK;
325 }
326 
327 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
328 {
329 	if (user_mode(ctxt->regs))
330 		return __vc_decode_user_insn(ctxt);
331 	else
332 		return __vc_decode_kern_insn(ctxt);
333 }
334 
335 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
336 				   char *dst, char *buf, size_t size)
337 {
338 	unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
339 
340 	/*
341 	 * This function uses __put_user() independent of whether kernel or user
342 	 * memory is accessed. This works fine because __put_user() does no
343 	 * sanity checks of the pointer being accessed. All that it does is
344 	 * to report when the access failed.
345 	 *
346 	 * Also, this function runs in atomic context, so __put_user() is not
347 	 * allowed to sleep. The page-fault handler detects that it is running
348 	 * in atomic context and will not try to take mmap_sem and handle the
349 	 * fault, so additional pagefault_enable()/disable() calls are not
350 	 * needed.
351 	 *
352 	 * The access can't be done via copy_to_user() here because
353 	 * vc_write_mem() must not use string instructions to access unsafe
354 	 * memory. The reason is that MOVS is emulated by the #VC handler by
355 	 * splitting the move up into a read and a write and taking a nested #VC
356 	 * exception on whatever of them is the MMIO access. Using string
357 	 * instructions here would cause infinite nesting.
358 	 */
359 	switch (size) {
360 	case 1: {
361 		u8 d1;
362 		u8 __user *target = (u8 __user *)dst;
363 
364 		memcpy(&d1, buf, 1);
365 		if (__put_user(d1, target))
366 			goto fault;
367 		break;
368 	}
369 	case 2: {
370 		u16 d2;
371 		u16 __user *target = (u16 __user *)dst;
372 
373 		memcpy(&d2, buf, 2);
374 		if (__put_user(d2, target))
375 			goto fault;
376 		break;
377 	}
378 	case 4: {
379 		u32 d4;
380 		u32 __user *target = (u32 __user *)dst;
381 
382 		memcpy(&d4, buf, 4);
383 		if (__put_user(d4, target))
384 			goto fault;
385 		break;
386 	}
387 	case 8: {
388 		u64 d8;
389 		u64 __user *target = (u64 __user *)dst;
390 
391 		memcpy(&d8, buf, 8);
392 		if (__put_user(d8, target))
393 			goto fault;
394 		break;
395 	}
396 	default:
397 		WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
398 		return ES_UNSUPPORTED;
399 	}
400 
401 	return ES_OK;
402 
403 fault:
404 	if (user_mode(ctxt->regs))
405 		error_code |= X86_PF_USER;
406 
407 	ctxt->fi.vector = X86_TRAP_PF;
408 	ctxt->fi.error_code = error_code;
409 	ctxt->fi.cr2 = (unsigned long)dst;
410 
411 	return ES_EXCEPTION;
412 }
413 
414 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
415 				  char *src, char *buf, size_t size)
416 {
417 	unsigned long error_code = X86_PF_PROT;
418 
419 	/*
420 	 * This function uses __get_user() independent of whether kernel or user
421 	 * memory is accessed. This works fine because __get_user() does no
422 	 * sanity checks of the pointer being accessed. All that it does is
423 	 * to report when the access failed.
424 	 *
425 	 * Also, this function runs in atomic context, so __get_user() is not
426 	 * allowed to sleep. The page-fault handler detects that it is running
427 	 * in atomic context and will not try to take mmap_sem and handle the
428 	 * fault, so additional pagefault_enable()/disable() calls are not
429 	 * needed.
430 	 *
431 	 * The access can't be done via copy_from_user() here because
432 	 * vc_read_mem() must not use string instructions to access unsafe
433 	 * memory. The reason is that MOVS is emulated by the #VC handler by
434 	 * splitting the move up into a read and a write and taking a nested #VC
435 	 * exception on whatever of them is the MMIO access. Using string
436 	 * instructions here would cause infinite nesting.
437 	 */
438 	switch (size) {
439 	case 1: {
440 		u8 d1;
441 		u8 __user *s = (u8 __user *)src;
442 
443 		if (__get_user(d1, s))
444 			goto fault;
445 		memcpy(buf, &d1, 1);
446 		break;
447 	}
448 	case 2: {
449 		u16 d2;
450 		u16 __user *s = (u16 __user *)src;
451 
452 		if (__get_user(d2, s))
453 			goto fault;
454 		memcpy(buf, &d2, 2);
455 		break;
456 	}
457 	case 4: {
458 		u32 d4;
459 		u32 __user *s = (u32 __user *)src;
460 
461 		if (__get_user(d4, s))
462 			goto fault;
463 		memcpy(buf, &d4, 4);
464 		break;
465 	}
466 	case 8: {
467 		u64 d8;
468 		u64 __user *s = (u64 __user *)src;
469 		if (__get_user(d8, s))
470 			goto fault;
471 		memcpy(buf, &d8, 8);
472 		break;
473 	}
474 	default:
475 		WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
476 		return ES_UNSUPPORTED;
477 	}
478 
479 	return ES_OK;
480 
481 fault:
482 	if (user_mode(ctxt->regs))
483 		error_code |= X86_PF_USER;
484 
485 	ctxt->fi.vector = X86_TRAP_PF;
486 	ctxt->fi.error_code = error_code;
487 	ctxt->fi.cr2 = (unsigned long)src;
488 
489 	return ES_EXCEPTION;
490 }
491 
492 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
493 					   unsigned long vaddr, phys_addr_t *paddr)
494 {
495 	unsigned long va = (unsigned long)vaddr;
496 	unsigned int level;
497 	phys_addr_t pa;
498 	pgd_t *pgd;
499 	pte_t *pte;
500 
501 	pgd = __va(read_cr3_pa());
502 	pgd = &pgd[pgd_index(va)];
503 	pte = lookup_address_in_pgd(pgd, va, &level);
504 	if (!pte) {
505 		ctxt->fi.vector     = X86_TRAP_PF;
506 		ctxt->fi.cr2        = vaddr;
507 		ctxt->fi.error_code = 0;
508 
509 		if (user_mode(ctxt->regs))
510 			ctxt->fi.error_code |= X86_PF_USER;
511 
512 		return ES_EXCEPTION;
513 	}
514 
515 	if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
516 		/* Emulated MMIO to/from encrypted memory not supported */
517 		return ES_UNSUPPORTED;
518 
519 	pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
520 	pa |= va & ~page_level_mask(level);
521 
522 	*paddr = pa;
523 
524 	return ES_OK;
525 }
526 
527 /* Include code shared with pre-decompression boot stage */
528 #include "sev-shared.c"
529 
530 static noinstr void __sev_put_ghcb(struct ghcb_state *state)
531 {
532 	struct sev_es_runtime_data *data;
533 	struct ghcb *ghcb;
534 
535 	WARN_ON(!irqs_disabled());
536 
537 	data = this_cpu_read(runtime_data);
538 	ghcb = &data->ghcb_page;
539 
540 	if (state->ghcb) {
541 		/* Restore GHCB from Backup */
542 		*ghcb = *state->ghcb;
543 		data->backup_ghcb_active = false;
544 		state->ghcb = NULL;
545 	} else {
546 		/*
547 		 * Invalidate the GHCB so a VMGEXIT instruction issued
548 		 * from userspace won't appear to be valid.
549 		 */
550 		vc_ghcb_invalidate(ghcb);
551 		data->ghcb_active = false;
552 	}
553 }
554 
555 void noinstr __sev_es_nmi_complete(void)
556 {
557 	struct ghcb_state state;
558 	struct ghcb *ghcb;
559 
560 	ghcb = __sev_get_ghcb(&state);
561 
562 	vc_ghcb_invalidate(ghcb);
563 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
564 	ghcb_set_sw_exit_info_1(ghcb, 0);
565 	ghcb_set_sw_exit_info_2(ghcb, 0);
566 
567 	sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
568 	VMGEXIT();
569 
570 	__sev_put_ghcb(&state);
571 }
572 
573 static u64 __init get_secrets_page(void)
574 {
575 	u64 pa_data = boot_params.cc_blob_address;
576 	struct cc_blob_sev_info info;
577 	void *map;
578 
579 	/*
580 	 * The CC blob contains the address of the secrets page, check if the
581 	 * blob is present.
582 	 */
583 	if (!pa_data)
584 		return 0;
585 
586 	map = early_memremap(pa_data, sizeof(info));
587 	if (!map) {
588 		pr_err("Unable to locate SNP secrets page: failed to map the Confidential Computing blob.\n");
589 		return 0;
590 	}
591 	memcpy(&info, map, sizeof(info));
592 	early_memunmap(map, sizeof(info));
593 
594 	/* smoke-test the secrets page passed */
595 	if (!info.secrets_phys || info.secrets_len != PAGE_SIZE)
596 		return 0;
597 
598 	return info.secrets_phys;
599 }
600 
601 static u64 __init get_snp_jump_table_addr(void)
602 {
603 	struct snp_secrets_page_layout *layout;
604 	void __iomem *mem;
605 	u64 pa, addr;
606 
607 	pa = get_secrets_page();
608 	if (!pa)
609 		return 0;
610 
611 	mem = ioremap_encrypted(pa, PAGE_SIZE);
612 	if (!mem) {
613 		pr_err("Unable to locate AP jump table address: failed to map the SNP secrets page.\n");
614 		return 0;
615 	}
616 
617 	layout = (__force struct snp_secrets_page_layout *)mem;
618 
619 	addr = layout->os_area.ap_jump_table_pa;
620 	iounmap(mem);
621 
622 	return addr;
623 }
624 
625 static u64 __init get_jump_table_addr(void)
626 {
627 	struct ghcb_state state;
628 	unsigned long flags;
629 	struct ghcb *ghcb;
630 	u64 ret = 0;
631 
632 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
633 		return get_snp_jump_table_addr();
634 
635 	local_irq_save(flags);
636 
637 	ghcb = __sev_get_ghcb(&state);
638 
639 	vc_ghcb_invalidate(ghcb);
640 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
641 	ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
642 	ghcb_set_sw_exit_info_2(ghcb, 0);
643 
644 	sev_es_wr_ghcb_msr(__pa(ghcb));
645 	VMGEXIT();
646 
647 	if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
648 	    ghcb_sw_exit_info_2_is_valid(ghcb))
649 		ret = ghcb->save.sw_exit_info_2;
650 
651 	__sev_put_ghcb(&state);
652 
653 	local_irq_restore(flags);
654 
655 	return ret;
656 }
657 
658 static void early_set_pages_state(unsigned long vaddr, unsigned long paddr,
659 				  unsigned long npages, enum psc_op op)
660 {
661 	unsigned long paddr_end;
662 	u64 val;
663 	int ret;
664 
665 	vaddr = vaddr & PAGE_MASK;
666 
667 	paddr = paddr & PAGE_MASK;
668 	paddr_end = paddr + (npages << PAGE_SHIFT);
669 
670 	while (paddr < paddr_end) {
671 		if (op == SNP_PAGE_STATE_SHARED) {
672 			/* Page validation must be rescinded before changing to shared */
673 			ret = pvalidate(vaddr, RMP_PG_SIZE_4K, false);
674 			if (WARN(ret, "Failed to validate address 0x%lx ret %d", paddr, ret))
675 				goto e_term;
676 		}
677 
678 		/*
679 		 * Use the MSR protocol because this function can be called before
680 		 * the GHCB is established.
681 		 */
682 		sev_es_wr_ghcb_msr(GHCB_MSR_PSC_REQ_GFN(paddr >> PAGE_SHIFT, op));
683 		VMGEXIT();
684 
685 		val = sev_es_rd_ghcb_msr();
686 
687 		if (WARN(GHCB_RESP_CODE(val) != GHCB_MSR_PSC_RESP,
688 			 "Wrong PSC response code: 0x%x\n",
689 			 (unsigned int)GHCB_RESP_CODE(val)))
690 			goto e_term;
691 
692 		if (WARN(GHCB_MSR_PSC_RESP_VAL(val),
693 			 "Failed to change page state to '%s' paddr 0x%lx error 0x%llx\n",
694 			 op == SNP_PAGE_STATE_PRIVATE ? "private" : "shared",
695 			 paddr, GHCB_MSR_PSC_RESP_VAL(val)))
696 			goto e_term;
697 
698 		if (op == SNP_PAGE_STATE_PRIVATE) {
699 			/* Page validation must be performed after changing to private */
700 			ret = pvalidate(vaddr, RMP_PG_SIZE_4K, true);
701 			if (WARN(ret, "Failed to validate address 0x%lx ret %d", paddr, ret))
702 				goto e_term;
703 		}
704 
705 		vaddr += PAGE_SIZE;
706 		paddr += PAGE_SIZE;
707 	}
708 
709 	return;
710 
711 e_term:
712 	sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
713 }
714 
715 void __init early_snp_set_memory_private(unsigned long vaddr, unsigned long paddr,
716 					 unsigned long npages)
717 {
718 	/*
719 	 * This can be invoked in early boot while running identity mapped, so
720 	 * use an open coded check for SNP instead of using cc_platform_has().
721 	 * This eliminates worries about jump tables or checking boot_cpu_data
722 	 * in the cc_platform_has() function.
723 	 */
724 	if (!(sev_status & MSR_AMD64_SEV_SNP_ENABLED))
725 		return;
726 
727 	 /*
728 	  * Ask the hypervisor to mark the memory pages as private in the RMP
729 	  * table.
730 	  */
731 	early_set_pages_state(vaddr, paddr, npages, SNP_PAGE_STATE_PRIVATE);
732 }
733 
734 void __init early_snp_set_memory_shared(unsigned long vaddr, unsigned long paddr,
735 					unsigned long npages)
736 {
737 	/*
738 	 * This can be invoked in early boot while running identity mapped, so
739 	 * use an open coded check for SNP instead of using cc_platform_has().
740 	 * This eliminates worries about jump tables or checking boot_cpu_data
741 	 * in the cc_platform_has() function.
742 	 */
743 	if (!(sev_status & MSR_AMD64_SEV_SNP_ENABLED))
744 		return;
745 
746 	 /* Ask hypervisor to mark the memory pages shared in the RMP table. */
747 	early_set_pages_state(vaddr, paddr, npages, SNP_PAGE_STATE_SHARED);
748 }
749 
750 void __init snp_prep_memory(unsigned long paddr, unsigned int sz, enum psc_op op)
751 {
752 	unsigned long vaddr, npages;
753 
754 	vaddr = (unsigned long)__va(paddr);
755 	npages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
756 
757 	if (op == SNP_PAGE_STATE_PRIVATE)
758 		early_snp_set_memory_private(vaddr, paddr, npages);
759 	else if (op == SNP_PAGE_STATE_SHARED)
760 		early_snp_set_memory_shared(vaddr, paddr, npages);
761 	else
762 		WARN(1, "invalid memory op %d\n", op);
763 }
764 
765 static unsigned long __set_pages_state(struct snp_psc_desc *data, unsigned long vaddr,
766 				       unsigned long vaddr_end, int op)
767 {
768 	struct ghcb_state state;
769 	bool use_large_entry;
770 	struct psc_hdr *hdr;
771 	struct psc_entry *e;
772 	unsigned long flags;
773 	unsigned long pfn;
774 	struct ghcb *ghcb;
775 	int i;
776 
777 	hdr = &data->hdr;
778 	e = data->entries;
779 
780 	memset(data, 0, sizeof(*data));
781 	i = 0;
782 
783 	while (vaddr < vaddr_end && i < ARRAY_SIZE(data->entries)) {
784 		hdr->end_entry = i;
785 
786 		if (is_vmalloc_addr((void *)vaddr)) {
787 			pfn = vmalloc_to_pfn((void *)vaddr);
788 			use_large_entry = false;
789 		} else {
790 			pfn = __pa(vaddr) >> PAGE_SHIFT;
791 			use_large_entry = true;
792 		}
793 
794 		e->gfn = pfn;
795 		e->operation = op;
796 
797 		if (use_large_entry && IS_ALIGNED(vaddr, PMD_SIZE) &&
798 		    (vaddr_end - vaddr) >= PMD_SIZE) {
799 			e->pagesize = RMP_PG_SIZE_2M;
800 			vaddr += PMD_SIZE;
801 		} else {
802 			e->pagesize = RMP_PG_SIZE_4K;
803 			vaddr += PAGE_SIZE;
804 		}
805 
806 		e++;
807 		i++;
808 	}
809 
810 	/* Page validation must be rescinded before changing to shared */
811 	if (op == SNP_PAGE_STATE_SHARED)
812 		pvalidate_pages(data);
813 
814 	local_irq_save(flags);
815 
816 	if (sev_cfg.ghcbs_initialized)
817 		ghcb = __sev_get_ghcb(&state);
818 	else
819 		ghcb = boot_ghcb;
820 
821 	/* Invoke the hypervisor to perform the page state changes */
822 	if (!ghcb || vmgexit_psc(ghcb, data))
823 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
824 
825 	if (sev_cfg.ghcbs_initialized)
826 		__sev_put_ghcb(&state);
827 
828 	local_irq_restore(flags);
829 
830 	/* Page validation must be performed after changing to private */
831 	if (op == SNP_PAGE_STATE_PRIVATE)
832 		pvalidate_pages(data);
833 
834 	return vaddr;
835 }
836 
837 static void set_pages_state(unsigned long vaddr, unsigned long npages, int op)
838 {
839 	struct snp_psc_desc desc;
840 	unsigned long vaddr_end;
841 
842 	/* Use the MSR protocol when a GHCB is not available. */
843 	if (!boot_ghcb)
844 		return early_set_pages_state(vaddr, __pa(vaddr), npages, op);
845 
846 	vaddr = vaddr & PAGE_MASK;
847 	vaddr_end = vaddr + (npages << PAGE_SHIFT);
848 
849 	while (vaddr < vaddr_end)
850 		vaddr = __set_pages_state(&desc, vaddr, vaddr_end, op);
851 }
852 
853 void snp_set_memory_shared(unsigned long vaddr, unsigned long npages)
854 {
855 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
856 		return;
857 
858 	set_pages_state(vaddr, npages, SNP_PAGE_STATE_SHARED);
859 }
860 
861 void snp_set_memory_private(unsigned long vaddr, unsigned long npages)
862 {
863 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
864 		return;
865 
866 	set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE);
867 }
868 
869 void snp_accept_memory(phys_addr_t start, phys_addr_t end)
870 {
871 	unsigned long vaddr;
872 	unsigned int npages;
873 
874 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
875 		return;
876 
877 	vaddr = (unsigned long)__va(start);
878 	npages = (end - start) >> PAGE_SHIFT;
879 
880 	set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE);
881 }
882 
883 static int snp_set_vmsa(void *va, bool vmsa)
884 {
885 	u64 attrs;
886 
887 	/*
888 	 * Running at VMPL0 allows the kernel to change the VMSA bit for a page
889 	 * using the RMPADJUST instruction. However, for the instruction to
890 	 * succeed it must target the permissions of a lesser privileged
891 	 * (higher numbered) VMPL level, so use VMPL1 (refer to the RMPADJUST
892 	 * instruction in the AMD64 APM Volume 3).
893 	 */
894 	attrs = 1;
895 	if (vmsa)
896 		attrs |= RMPADJUST_VMSA_PAGE_BIT;
897 
898 	return rmpadjust((unsigned long)va, RMP_PG_SIZE_4K, attrs);
899 }
900 
901 #define __ATTR_BASE		(SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK)
902 #define INIT_CS_ATTRIBS		(__ATTR_BASE | SVM_SELECTOR_READ_MASK | SVM_SELECTOR_CODE_MASK)
903 #define INIT_DS_ATTRIBS		(__ATTR_BASE | SVM_SELECTOR_WRITE_MASK)
904 
905 #define INIT_LDTR_ATTRIBS	(SVM_SELECTOR_P_MASK | 2)
906 #define INIT_TR_ATTRIBS		(SVM_SELECTOR_P_MASK | 3)
907 
908 static void *snp_alloc_vmsa_page(void)
909 {
910 	struct page *p;
911 
912 	/*
913 	 * Allocate VMSA page to work around the SNP erratum where the CPU will
914 	 * incorrectly signal an RMP violation #PF if a large page (2MB or 1GB)
915 	 * collides with the RMP entry of VMSA page. The recommended workaround
916 	 * is to not use a large page.
917 	 *
918 	 * Allocate an 8k page which is also 8k-aligned.
919 	 */
920 	p = alloc_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO, 1);
921 	if (!p)
922 		return NULL;
923 
924 	split_page(p, 1);
925 
926 	/* Free the first 4k. This page may be 2M/1G aligned and cannot be used. */
927 	__free_page(p);
928 
929 	return page_address(p + 1);
930 }
931 
932 static void snp_cleanup_vmsa(struct sev_es_save_area *vmsa)
933 {
934 	int err;
935 
936 	err = snp_set_vmsa(vmsa, false);
937 	if (err)
938 		pr_err("clear VMSA page failed (%u), leaking page\n", err);
939 	else
940 		free_page((unsigned long)vmsa);
941 }
942 
943 static int wakeup_cpu_via_vmgexit(int apic_id, unsigned long start_ip)
944 {
945 	struct sev_es_save_area *cur_vmsa, *vmsa;
946 	struct ghcb_state state;
947 	unsigned long flags;
948 	struct ghcb *ghcb;
949 	u8 sipi_vector;
950 	int cpu, ret;
951 	u64 cr4;
952 
953 	/*
954 	 * The hypervisor SNP feature support check has happened earlier, just check
955 	 * the AP_CREATION one here.
956 	 */
957 	if (!(sev_hv_features & GHCB_HV_FT_SNP_AP_CREATION))
958 		return -EOPNOTSUPP;
959 
960 	/*
961 	 * Verify the desired start IP against the known trampoline start IP
962 	 * to catch any future new trampolines that may be introduced that
963 	 * would require a new protected guest entry point.
964 	 */
965 	if (WARN_ONCE(start_ip != real_mode_header->trampoline_start,
966 		      "Unsupported SNP start_ip: %lx\n", start_ip))
967 		return -EINVAL;
968 
969 	/* Override start_ip with known protected guest start IP */
970 	start_ip = real_mode_header->sev_es_trampoline_start;
971 
972 	/* Find the logical CPU for the APIC ID */
973 	for_each_present_cpu(cpu) {
974 		if (arch_match_cpu_phys_id(cpu, apic_id))
975 			break;
976 	}
977 	if (cpu >= nr_cpu_ids)
978 		return -EINVAL;
979 
980 	cur_vmsa = per_cpu(sev_vmsa, cpu);
981 
982 	/*
983 	 * A new VMSA is created each time because there is no guarantee that
984 	 * the current VMSA is the kernels or that the vCPU is not running. If
985 	 * an attempt was done to use the current VMSA with a running vCPU, a
986 	 * #VMEXIT of that vCPU would wipe out all of the settings being done
987 	 * here.
988 	 */
989 	vmsa = (struct sev_es_save_area *)snp_alloc_vmsa_page();
990 	if (!vmsa)
991 		return -ENOMEM;
992 
993 	/* CR4 should maintain the MCE value */
994 	cr4 = native_read_cr4() & X86_CR4_MCE;
995 
996 	/* Set the CS value based on the start_ip converted to a SIPI vector */
997 	sipi_vector		= (start_ip >> 12);
998 	vmsa->cs.base		= sipi_vector << 12;
999 	vmsa->cs.limit		= AP_INIT_CS_LIMIT;
1000 	vmsa->cs.attrib		= INIT_CS_ATTRIBS;
1001 	vmsa->cs.selector	= sipi_vector << 8;
1002 
1003 	/* Set the RIP value based on start_ip */
1004 	vmsa->rip		= start_ip & 0xfff;
1005 
1006 	/* Set AP INIT defaults as documented in the APM */
1007 	vmsa->ds.limit		= AP_INIT_DS_LIMIT;
1008 	vmsa->ds.attrib		= INIT_DS_ATTRIBS;
1009 	vmsa->es		= vmsa->ds;
1010 	vmsa->fs		= vmsa->ds;
1011 	vmsa->gs		= vmsa->ds;
1012 	vmsa->ss		= vmsa->ds;
1013 
1014 	vmsa->gdtr.limit	= AP_INIT_GDTR_LIMIT;
1015 	vmsa->ldtr.limit	= AP_INIT_LDTR_LIMIT;
1016 	vmsa->ldtr.attrib	= INIT_LDTR_ATTRIBS;
1017 	vmsa->idtr.limit	= AP_INIT_IDTR_LIMIT;
1018 	vmsa->tr.limit		= AP_INIT_TR_LIMIT;
1019 	vmsa->tr.attrib		= INIT_TR_ATTRIBS;
1020 
1021 	vmsa->cr4		= cr4;
1022 	vmsa->cr0		= AP_INIT_CR0_DEFAULT;
1023 	vmsa->dr7		= DR7_RESET_VALUE;
1024 	vmsa->dr6		= AP_INIT_DR6_DEFAULT;
1025 	vmsa->rflags		= AP_INIT_RFLAGS_DEFAULT;
1026 	vmsa->g_pat		= AP_INIT_GPAT_DEFAULT;
1027 	vmsa->xcr0		= AP_INIT_XCR0_DEFAULT;
1028 	vmsa->mxcsr		= AP_INIT_MXCSR_DEFAULT;
1029 	vmsa->x87_ftw		= AP_INIT_X87_FTW_DEFAULT;
1030 	vmsa->x87_fcw		= AP_INIT_X87_FCW_DEFAULT;
1031 
1032 	/* SVME must be set. */
1033 	vmsa->efer		= EFER_SVME;
1034 
1035 	/*
1036 	 * Set the SNP-specific fields for this VMSA:
1037 	 *   VMPL level
1038 	 *   SEV_FEATURES (matches the SEV STATUS MSR right shifted 2 bits)
1039 	 */
1040 	vmsa->vmpl		= 0;
1041 	vmsa->sev_features	= sev_status >> 2;
1042 
1043 	/* Switch the page over to a VMSA page now that it is initialized */
1044 	ret = snp_set_vmsa(vmsa, true);
1045 	if (ret) {
1046 		pr_err("set VMSA page failed (%u)\n", ret);
1047 		free_page((unsigned long)vmsa);
1048 
1049 		return -EINVAL;
1050 	}
1051 
1052 	/* Issue VMGEXIT AP Creation NAE event */
1053 	local_irq_save(flags);
1054 
1055 	ghcb = __sev_get_ghcb(&state);
1056 
1057 	vc_ghcb_invalidate(ghcb);
1058 	ghcb_set_rax(ghcb, vmsa->sev_features);
1059 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_CREATION);
1060 	ghcb_set_sw_exit_info_1(ghcb, ((u64)apic_id << 32) | SVM_VMGEXIT_AP_CREATE);
1061 	ghcb_set_sw_exit_info_2(ghcb, __pa(vmsa));
1062 
1063 	sev_es_wr_ghcb_msr(__pa(ghcb));
1064 	VMGEXIT();
1065 
1066 	if (!ghcb_sw_exit_info_1_is_valid(ghcb) ||
1067 	    lower_32_bits(ghcb->save.sw_exit_info_1)) {
1068 		pr_err("SNP AP Creation error\n");
1069 		ret = -EINVAL;
1070 	}
1071 
1072 	__sev_put_ghcb(&state);
1073 
1074 	local_irq_restore(flags);
1075 
1076 	/* Perform cleanup if there was an error */
1077 	if (ret) {
1078 		snp_cleanup_vmsa(vmsa);
1079 		vmsa = NULL;
1080 	}
1081 
1082 	/* Free up any previous VMSA page */
1083 	if (cur_vmsa)
1084 		snp_cleanup_vmsa(cur_vmsa);
1085 
1086 	/* Record the current VMSA page */
1087 	per_cpu(sev_vmsa, cpu) = vmsa;
1088 
1089 	return ret;
1090 }
1091 
1092 void snp_set_wakeup_secondary_cpu(void)
1093 {
1094 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1095 		return;
1096 
1097 	/*
1098 	 * Always set this override if SNP is enabled. This makes it the
1099 	 * required method to start APs under SNP. If the hypervisor does
1100 	 * not support AP creation, then no APs will be started.
1101 	 */
1102 	apic->wakeup_secondary_cpu = wakeup_cpu_via_vmgexit;
1103 }
1104 
1105 int __init sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
1106 {
1107 	u16 startup_cs, startup_ip;
1108 	phys_addr_t jump_table_pa;
1109 	u64 jump_table_addr;
1110 	u16 __iomem *jump_table;
1111 
1112 	jump_table_addr = get_jump_table_addr();
1113 
1114 	/* On UP guests there is no jump table so this is not a failure */
1115 	if (!jump_table_addr)
1116 		return 0;
1117 
1118 	/* Check if AP Jump Table is page-aligned */
1119 	if (jump_table_addr & ~PAGE_MASK)
1120 		return -EINVAL;
1121 
1122 	jump_table_pa = jump_table_addr & PAGE_MASK;
1123 
1124 	startup_cs = (u16)(rmh->trampoline_start >> 4);
1125 	startup_ip = (u16)(rmh->sev_es_trampoline_start -
1126 			   rmh->trampoline_start);
1127 
1128 	jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
1129 	if (!jump_table)
1130 		return -EIO;
1131 
1132 	writew(startup_ip, &jump_table[0]);
1133 	writew(startup_cs, &jump_table[1]);
1134 
1135 	iounmap(jump_table);
1136 
1137 	return 0;
1138 }
1139 
1140 /*
1141  * This is needed by the OVMF UEFI firmware which will use whatever it finds in
1142  * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
1143  * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
1144  */
1145 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
1146 {
1147 	struct sev_es_runtime_data *data;
1148 	unsigned long address, pflags;
1149 	int cpu;
1150 	u64 pfn;
1151 
1152 	if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1153 		return 0;
1154 
1155 	pflags = _PAGE_NX | _PAGE_RW;
1156 
1157 	for_each_possible_cpu(cpu) {
1158 		data = per_cpu(runtime_data, cpu);
1159 
1160 		address = __pa(&data->ghcb_page);
1161 		pfn = address >> PAGE_SHIFT;
1162 
1163 		if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
1164 			return 1;
1165 	}
1166 
1167 	return 0;
1168 }
1169 
1170 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1171 {
1172 	struct pt_regs *regs = ctxt->regs;
1173 	enum es_result ret;
1174 	u64 exit_info_1;
1175 
1176 	/* Is it a WRMSR? */
1177 	exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
1178 
1179 	ghcb_set_rcx(ghcb, regs->cx);
1180 	if (exit_info_1) {
1181 		ghcb_set_rax(ghcb, regs->ax);
1182 		ghcb_set_rdx(ghcb, regs->dx);
1183 	}
1184 
1185 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, exit_info_1, 0);
1186 
1187 	if ((ret == ES_OK) && (!exit_info_1)) {
1188 		regs->ax = ghcb->save.rax;
1189 		regs->dx = ghcb->save.rdx;
1190 	}
1191 
1192 	return ret;
1193 }
1194 
1195 static void snp_register_per_cpu_ghcb(void)
1196 {
1197 	struct sev_es_runtime_data *data;
1198 	struct ghcb *ghcb;
1199 
1200 	data = this_cpu_read(runtime_data);
1201 	ghcb = &data->ghcb_page;
1202 
1203 	snp_register_ghcb_early(__pa(ghcb));
1204 }
1205 
1206 void setup_ghcb(void)
1207 {
1208 	if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1209 		return;
1210 
1211 	/* First make sure the hypervisor talks a supported protocol. */
1212 	if (!sev_es_negotiate_protocol())
1213 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
1214 
1215 	/*
1216 	 * Check whether the runtime #VC exception handler is active. It uses
1217 	 * the per-CPU GHCB page which is set up by sev_es_init_vc_handling().
1218 	 *
1219 	 * If SNP is active, register the per-CPU GHCB page so that the runtime
1220 	 * exception handler can use it.
1221 	 */
1222 	if (initial_vc_handler == (unsigned long)kernel_exc_vmm_communication) {
1223 		if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1224 			snp_register_per_cpu_ghcb();
1225 
1226 		sev_cfg.ghcbs_initialized = true;
1227 
1228 		return;
1229 	}
1230 
1231 	/*
1232 	 * Clear the boot_ghcb. The first exception comes in before the bss
1233 	 * section is cleared.
1234 	 */
1235 	memset(&boot_ghcb_page, 0, PAGE_SIZE);
1236 
1237 	/* Alright - Make the boot-ghcb public */
1238 	boot_ghcb = &boot_ghcb_page;
1239 
1240 	/* SNP guest requires that GHCB GPA must be registered. */
1241 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1242 		snp_register_ghcb_early(__pa(&boot_ghcb_page));
1243 }
1244 
1245 #ifdef CONFIG_HOTPLUG_CPU
1246 static void sev_es_ap_hlt_loop(void)
1247 {
1248 	struct ghcb_state state;
1249 	struct ghcb *ghcb;
1250 
1251 	ghcb = __sev_get_ghcb(&state);
1252 
1253 	while (true) {
1254 		vc_ghcb_invalidate(ghcb);
1255 		ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
1256 		ghcb_set_sw_exit_info_1(ghcb, 0);
1257 		ghcb_set_sw_exit_info_2(ghcb, 0);
1258 
1259 		sev_es_wr_ghcb_msr(__pa(ghcb));
1260 		VMGEXIT();
1261 
1262 		/* Wakeup signal? */
1263 		if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
1264 		    ghcb->save.sw_exit_info_2)
1265 			break;
1266 	}
1267 
1268 	__sev_put_ghcb(&state);
1269 }
1270 
1271 /*
1272  * Play_dead handler when running under SEV-ES. This is needed because
1273  * the hypervisor can't deliver an SIPI request to restart the AP.
1274  * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
1275  * hypervisor wakes it up again.
1276  */
1277 static void sev_es_play_dead(void)
1278 {
1279 	play_dead_common();
1280 
1281 	/* IRQs now disabled */
1282 
1283 	sev_es_ap_hlt_loop();
1284 
1285 	/*
1286 	 * If we get here, the VCPU was woken up again. Jump to CPU
1287 	 * startup code to get it back online.
1288 	 */
1289 	soft_restart_cpu();
1290 }
1291 #else  /* CONFIG_HOTPLUG_CPU */
1292 #define sev_es_play_dead	native_play_dead
1293 #endif /* CONFIG_HOTPLUG_CPU */
1294 
1295 #ifdef CONFIG_SMP
1296 static void __init sev_es_setup_play_dead(void)
1297 {
1298 	smp_ops.play_dead = sev_es_play_dead;
1299 }
1300 #else
1301 static inline void sev_es_setup_play_dead(void) { }
1302 #endif
1303 
1304 static void __init alloc_runtime_data(int cpu)
1305 {
1306 	struct sev_es_runtime_data *data;
1307 
1308 	data = memblock_alloc(sizeof(*data), PAGE_SIZE);
1309 	if (!data)
1310 		panic("Can't allocate SEV-ES runtime data");
1311 
1312 	per_cpu(runtime_data, cpu) = data;
1313 }
1314 
1315 static void __init init_ghcb(int cpu)
1316 {
1317 	struct sev_es_runtime_data *data;
1318 	int err;
1319 
1320 	data = per_cpu(runtime_data, cpu);
1321 
1322 	err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
1323 					 sizeof(data->ghcb_page));
1324 	if (err)
1325 		panic("Can't map GHCBs unencrypted");
1326 
1327 	memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
1328 
1329 	data->ghcb_active = false;
1330 	data->backup_ghcb_active = false;
1331 }
1332 
1333 void __init sev_es_init_vc_handling(void)
1334 {
1335 	int cpu;
1336 
1337 	BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
1338 
1339 	if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1340 		return;
1341 
1342 	if (!sev_es_check_cpu_features())
1343 		panic("SEV-ES CPU Features missing");
1344 
1345 	/*
1346 	 * SNP is supported in v2 of the GHCB spec which mandates support for HV
1347 	 * features.
1348 	 */
1349 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) {
1350 		sev_hv_features = get_hv_features();
1351 
1352 		if (!(sev_hv_features & GHCB_HV_FT_SNP))
1353 			sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
1354 	}
1355 
1356 	/* Initialize per-cpu GHCB pages */
1357 	for_each_possible_cpu(cpu) {
1358 		alloc_runtime_data(cpu);
1359 		init_ghcb(cpu);
1360 	}
1361 
1362 	sev_es_setup_play_dead();
1363 
1364 	/* Secondary CPUs use the runtime #VC handler */
1365 	initial_vc_handler = (unsigned long)kernel_exc_vmm_communication;
1366 }
1367 
1368 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
1369 {
1370 	int trapnr = ctxt->fi.vector;
1371 
1372 	if (trapnr == X86_TRAP_PF)
1373 		native_write_cr2(ctxt->fi.cr2);
1374 
1375 	ctxt->regs->orig_ax = ctxt->fi.error_code;
1376 	do_early_exception(ctxt->regs, trapnr);
1377 }
1378 
1379 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
1380 {
1381 	long *reg_array;
1382 	int offset;
1383 
1384 	reg_array = (long *)ctxt->regs;
1385 	offset    = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
1386 
1387 	if (offset < 0)
1388 		return NULL;
1389 
1390 	offset /= sizeof(long);
1391 
1392 	return reg_array + offset;
1393 }
1394 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
1395 				 unsigned int bytes, bool read)
1396 {
1397 	u64 exit_code, exit_info_1, exit_info_2;
1398 	unsigned long ghcb_pa = __pa(ghcb);
1399 	enum es_result res;
1400 	phys_addr_t paddr;
1401 	void __user *ref;
1402 
1403 	ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
1404 	if (ref == (void __user *)-1L)
1405 		return ES_UNSUPPORTED;
1406 
1407 	exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
1408 
1409 	res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
1410 	if (res != ES_OK) {
1411 		if (res == ES_EXCEPTION && !read)
1412 			ctxt->fi.error_code |= X86_PF_WRITE;
1413 
1414 		return res;
1415 	}
1416 
1417 	exit_info_1 = paddr;
1418 	/* Can never be greater than 8 */
1419 	exit_info_2 = bytes;
1420 
1421 	ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
1422 
1423 	return sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, exit_info_1, exit_info_2);
1424 }
1425 
1426 /*
1427  * The MOVS instruction has two memory operands, which raises the
1428  * problem that it is not known whether the access to the source or the
1429  * destination caused the #VC exception (and hence whether an MMIO read
1430  * or write operation needs to be emulated).
1431  *
1432  * Instead of playing games with walking page-tables and trying to guess
1433  * whether the source or destination is an MMIO range, split the move
1434  * into two operations, a read and a write with only one memory operand.
1435  * This will cause a nested #VC exception on the MMIO address which can
1436  * then be handled.
1437  *
1438  * This implementation has the benefit that it also supports MOVS where
1439  * source _and_ destination are MMIO regions.
1440  *
1441  * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
1442  * rare operation. If it turns out to be a performance problem the split
1443  * operations can be moved to memcpy_fromio() and memcpy_toio().
1444  */
1445 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
1446 					  unsigned int bytes)
1447 {
1448 	unsigned long ds_base, es_base;
1449 	unsigned char *src, *dst;
1450 	unsigned char buffer[8];
1451 	enum es_result ret;
1452 	bool rep;
1453 	int off;
1454 
1455 	ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
1456 	es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
1457 
1458 	if (ds_base == -1L || es_base == -1L) {
1459 		ctxt->fi.vector = X86_TRAP_GP;
1460 		ctxt->fi.error_code = 0;
1461 		return ES_EXCEPTION;
1462 	}
1463 
1464 	src = ds_base + (unsigned char *)ctxt->regs->si;
1465 	dst = es_base + (unsigned char *)ctxt->regs->di;
1466 
1467 	ret = vc_read_mem(ctxt, src, buffer, bytes);
1468 	if (ret != ES_OK)
1469 		return ret;
1470 
1471 	ret = vc_write_mem(ctxt, dst, buffer, bytes);
1472 	if (ret != ES_OK)
1473 		return ret;
1474 
1475 	if (ctxt->regs->flags & X86_EFLAGS_DF)
1476 		off = -bytes;
1477 	else
1478 		off =  bytes;
1479 
1480 	ctxt->regs->si += off;
1481 	ctxt->regs->di += off;
1482 
1483 	rep = insn_has_rep_prefix(&ctxt->insn);
1484 	if (rep)
1485 		ctxt->regs->cx -= 1;
1486 
1487 	if (!rep || ctxt->regs->cx == 0)
1488 		return ES_OK;
1489 	else
1490 		return ES_RETRY;
1491 }
1492 
1493 static enum es_result vc_handle_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1494 {
1495 	struct insn *insn = &ctxt->insn;
1496 	enum insn_mmio_type mmio;
1497 	unsigned int bytes = 0;
1498 	enum es_result ret;
1499 	u8 sign_byte;
1500 	long *reg_data;
1501 
1502 	mmio = insn_decode_mmio(insn, &bytes);
1503 	if (mmio == INSN_MMIO_DECODE_FAILED)
1504 		return ES_DECODE_FAILED;
1505 
1506 	if (mmio != INSN_MMIO_WRITE_IMM && mmio != INSN_MMIO_MOVS) {
1507 		reg_data = insn_get_modrm_reg_ptr(insn, ctxt->regs);
1508 		if (!reg_data)
1509 			return ES_DECODE_FAILED;
1510 	}
1511 
1512 	switch (mmio) {
1513 	case INSN_MMIO_WRITE:
1514 		memcpy(ghcb->shared_buffer, reg_data, bytes);
1515 		ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1516 		break;
1517 	case INSN_MMIO_WRITE_IMM:
1518 		memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
1519 		ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1520 		break;
1521 	case INSN_MMIO_READ:
1522 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1523 		if (ret)
1524 			break;
1525 
1526 		/* Zero-extend for 32-bit operation */
1527 		if (bytes == 4)
1528 			*reg_data = 0;
1529 
1530 		memcpy(reg_data, ghcb->shared_buffer, bytes);
1531 		break;
1532 	case INSN_MMIO_READ_ZERO_EXTEND:
1533 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1534 		if (ret)
1535 			break;
1536 
1537 		/* Zero extend based on operand size */
1538 		memset(reg_data, 0, insn->opnd_bytes);
1539 		memcpy(reg_data, ghcb->shared_buffer, bytes);
1540 		break;
1541 	case INSN_MMIO_READ_SIGN_EXTEND:
1542 		ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1543 		if (ret)
1544 			break;
1545 
1546 		if (bytes == 1) {
1547 			u8 *val = (u8 *)ghcb->shared_buffer;
1548 
1549 			sign_byte = (*val & 0x80) ? 0xff : 0x00;
1550 		} else {
1551 			u16 *val = (u16 *)ghcb->shared_buffer;
1552 
1553 			sign_byte = (*val & 0x8000) ? 0xff : 0x00;
1554 		}
1555 
1556 		/* Sign extend based on operand size */
1557 		memset(reg_data, sign_byte, insn->opnd_bytes);
1558 		memcpy(reg_data, ghcb->shared_buffer, bytes);
1559 		break;
1560 	case INSN_MMIO_MOVS:
1561 		ret = vc_handle_mmio_movs(ctxt, bytes);
1562 		break;
1563 	default:
1564 		ret = ES_UNSUPPORTED;
1565 		break;
1566 	}
1567 
1568 	return ret;
1569 }
1570 
1571 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1572 					  struct es_em_ctxt *ctxt)
1573 {
1574 	struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1575 	long val, *reg = vc_insn_get_rm(ctxt);
1576 	enum es_result ret;
1577 
1578 	if (!reg)
1579 		return ES_DECODE_FAILED;
1580 
1581 	val = *reg;
1582 
1583 	/* Upper 32 bits must be written as zeroes */
1584 	if (val >> 32) {
1585 		ctxt->fi.vector = X86_TRAP_GP;
1586 		ctxt->fi.error_code = 0;
1587 		return ES_EXCEPTION;
1588 	}
1589 
1590 	/* Clear out other reserved bits and set bit 10 */
1591 	val = (val & 0xffff23ffL) | BIT(10);
1592 
1593 	/* Early non-zero writes to DR7 are not supported */
1594 	if (!data && (val & ~DR7_RESET_VALUE))
1595 		return ES_UNSUPPORTED;
1596 
1597 	/* Using a value of 0 for ExitInfo1 means RAX holds the value */
1598 	ghcb_set_rax(ghcb, val);
1599 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1600 	if (ret != ES_OK)
1601 		return ret;
1602 
1603 	if (data)
1604 		data->dr7 = val;
1605 
1606 	return ES_OK;
1607 }
1608 
1609 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1610 					 struct es_em_ctxt *ctxt)
1611 {
1612 	struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1613 	long *reg = vc_insn_get_rm(ctxt);
1614 
1615 	if (!reg)
1616 		return ES_DECODE_FAILED;
1617 
1618 	if (data)
1619 		*reg = data->dr7;
1620 	else
1621 		*reg = DR7_RESET_VALUE;
1622 
1623 	return ES_OK;
1624 }
1625 
1626 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1627 				       struct es_em_ctxt *ctxt)
1628 {
1629 	return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
1630 }
1631 
1632 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1633 {
1634 	enum es_result ret;
1635 
1636 	ghcb_set_rcx(ghcb, ctxt->regs->cx);
1637 
1638 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
1639 	if (ret != ES_OK)
1640 		return ret;
1641 
1642 	if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1643 		return ES_VMM_ERROR;
1644 
1645 	ctxt->regs->ax = ghcb->save.rax;
1646 	ctxt->regs->dx = ghcb->save.rdx;
1647 
1648 	return ES_OK;
1649 }
1650 
1651 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1652 					struct es_em_ctxt *ctxt)
1653 {
1654 	/*
1655 	 * Treat it as a NOP and do not leak a physical address to the
1656 	 * hypervisor.
1657 	 */
1658 	return ES_OK;
1659 }
1660 
1661 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1662 				      struct es_em_ctxt *ctxt)
1663 {
1664 	/* Treat the same as MONITOR/MONITORX */
1665 	return ES_OK;
1666 }
1667 
1668 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1669 					struct es_em_ctxt *ctxt)
1670 {
1671 	enum es_result ret;
1672 
1673 	ghcb_set_rax(ghcb, ctxt->regs->ax);
1674 	ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1675 
1676 	if (x86_platform.hyper.sev_es_hcall_prepare)
1677 		x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1678 
1679 	ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1680 	if (ret != ES_OK)
1681 		return ret;
1682 
1683 	if (!ghcb_rax_is_valid(ghcb))
1684 		return ES_VMM_ERROR;
1685 
1686 	ctxt->regs->ax = ghcb->save.rax;
1687 
1688 	/*
1689 	 * Call sev_es_hcall_finish() after regs->ax is already set.
1690 	 * This allows the hypervisor handler to overwrite it again if
1691 	 * necessary.
1692 	 */
1693 	if (x86_platform.hyper.sev_es_hcall_finish &&
1694 	    !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1695 		return ES_VMM_ERROR;
1696 
1697 	return ES_OK;
1698 }
1699 
1700 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1701 					struct es_em_ctxt *ctxt)
1702 {
1703 	/*
1704 	 * Calling ecx_alignment_check() directly does not work, because it
1705 	 * enables IRQs and the GHCB is active. Forward the exception and call
1706 	 * it later from vc_forward_exception().
1707 	 */
1708 	ctxt->fi.vector = X86_TRAP_AC;
1709 	ctxt->fi.error_code = 0;
1710 	return ES_EXCEPTION;
1711 }
1712 
1713 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1714 					 struct ghcb *ghcb,
1715 					 unsigned long exit_code)
1716 {
1717 	enum es_result result;
1718 
1719 	switch (exit_code) {
1720 	case SVM_EXIT_READ_DR7:
1721 		result = vc_handle_dr7_read(ghcb, ctxt);
1722 		break;
1723 	case SVM_EXIT_WRITE_DR7:
1724 		result = vc_handle_dr7_write(ghcb, ctxt);
1725 		break;
1726 	case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1727 		result = vc_handle_trap_ac(ghcb, ctxt);
1728 		break;
1729 	case SVM_EXIT_RDTSC:
1730 	case SVM_EXIT_RDTSCP:
1731 		result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1732 		break;
1733 	case SVM_EXIT_RDPMC:
1734 		result = vc_handle_rdpmc(ghcb, ctxt);
1735 		break;
1736 	case SVM_EXIT_INVD:
1737 		pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1738 		result = ES_UNSUPPORTED;
1739 		break;
1740 	case SVM_EXIT_CPUID:
1741 		result = vc_handle_cpuid(ghcb, ctxt);
1742 		break;
1743 	case SVM_EXIT_IOIO:
1744 		result = vc_handle_ioio(ghcb, ctxt);
1745 		break;
1746 	case SVM_EXIT_MSR:
1747 		result = vc_handle_msr(ghcb, ctxt);
1748 		break;
1749 	case SVM_EXIT_VMMCALL:
1750 		result = vc_handle_vmmcall(ghcb, ctxt);
1751 		break;
1752 	case SVM_EXIT_WBINVD:
1753 		result = vc_handle_wbinvd(ghcb, ctxt);
1754 		break;
1755 	case SVM_EXIT_MONITOR:
1756 		result = vc_handle_monitor(ghcb, ctxt);
1757 		break;
1758 	case SVM_EXIT_MWAIT:
1759 		result = vc_handle_mwait(ghcb, ctxt);
1760 		break;
1761 	case SVM_EXIT_NPF:
1762 		result = vc_handle_mmio(ghcb, ctxt);
1763 		break;
1764 	default:
1765 		/*
1766 		 * Unexpected #VC exception
1767 		 */
1768 		result = ES_UNSUPPORTED;
1769 	}
1770 
1771 	return result;
1772 }
1773 
1774 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1775 {
1776 	long error_code = ctxt->fi.error_code;
1777 	int trapnr = ctxt->fi.vector;
1778 
1779 	ctxt->regs->orig_ax = ctxt->fi.error_code;
1780 
1781 	switch (trapnr) {
1782 	case X86_TRAP_GP:
1783 		exc_general_protection(ctxt->regs, error_code);
1784 		break;
1785 	case X86_TRAP_UD:
1786 		exc_invalid_op(ctxt->regs);
1787 		break;
1788 	case X86_TRAP_PF:
1789 		write_cr2(ctxt->fi.cr2);
1790 		exc_page_fault(ctxt->regs, error_code);
1791 		break;
1792 	case X86_TRAP_AC:
1793 		exc_alignment_check(ctxt->regs, error_code);
1794 		break;
1795 	default:
1796 		pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1797 		BUG();
1798 	}
1799 }
1800 
1801 static __always_inline bool is_vc2_stack(unsigned long sp)
1802 {
1803 	return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1804 }
1805 
1806 static __always_inline bool vc_from_invalid_context(struct pt_regs *regs)
1807 {
1808 	unsigned long sp, prev_sp;
1809 
1810 	sp      = (unsigned long)regs;
1811 	prev_sp = regs->sp;
1812 
1813 	/*
1814 	 * If the code was already executing on the VC2 stack when the #VC
1815 	 * happened, let it proceed to the normal handling routine. This way the
1816 	 * code executing on the VC2 stack can cause #VC exceptions to get handled.
1817 	 */
1818 	return is_vc2_stack(sp) && !is_vc2_stack(prev_sp);
1819 }
1820 
1821 static bool vc_raw_handle_exception(struct pt_regs *regs, unsigned long error_code)
1822 {
1823 	struct ghcb_state state;
1824 	struct es_em_ctxt ctxt;
1825 	enum es_result result;
1826 	struct ghcb *ghcb;
1827 	bool ret = true;
1828 
1829 	ghcb = __sev_get_ghcb(&state);
1830 
1831 	vc_ghcb_invalidate(ghcb);
1832 	result = vc_init_em_ctxt(&ctxt, regs, error_code);
1833 
1834 	if (result == ES_OK)
1835 		result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1836 
1837 	__sev_put_ghcb(&state);
1838 
1839 	/* Done - now check the result */
1840 	switch (result) {
1841 	case ES_OK:
1842 		vc_finish_insn(&ctxt);
1843 		break;
1844 	case ES_UNSUPPORTED:
1845 		pr_err_ratelimited("Unsupported exit-code 0x%02lx in #VC exception (IP: 0x%lx)\n",
1846 				   error_code, regs->ip);
1847 		ret = false;
1848 		break;
1849 	case ES_VMM_ERROR:
1850 		pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1851 				   error_code, regs->ip);
1852 		ret = false;
1853 		break;
1854 	case ES_DECODE_FAILED:
1855 		pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1856 				   error_code, regs->ip);
1857 		ret = false;
1858 		break;
1859 	case ES_EXCEPTION:
1860 		vc_forward_exception(&ctxt);
1861 		break;
1862 	case ES_RETRY:
1863 		/* Nothing to do */
1864 		break;
1865 	default:
1866 		pr_emerg("Unknown result in %s():%d\n", __func__, result);
1867 		/*
1868 		 * Emulating the instruction which caused the #VC exception
1869 		 * failed - can't continue so print debug information
1870 		 */
1871 		BUG();
1872 	}
1873 
1874 	return ret;
1875 }
1876 
1877 static __always_inline bool vc_is_db(unsigned long error_code)
1878 {
1879 	return error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB;
1880 }
1881 
1882 /*
1883  * Runtime #VC exception handler when raised from kernel mode. Runs in NMI mode
1884  * and will panic when an error happens.
1885  */
1886 DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)
1887 {
1888 	irqentry_state_t irq_state;
1889 
1890 	/*
1891 	 * With the current implementation it is always possible to switch to a
1892 	 * safe stack because #VC exceptions only happen at known places, like
1893 	 * intercepted instructions or accesses to MMIO areas/IO ports. They can
1894 	 * also happen with code instrumentation when the hypervisor intercepts
1895 	 * #DB, but the critical paths are forbidden to be instrumented, so #DB
1896 	 * exceptions currently also only happen in safe places.
1897 	 *
1898 	 * But keep this here in case the noinstr annotations are violated due
1899 	 * to bug elsewhere.
1900 	 */
1901 	if (unlikely(vc_from_invalid_context(regs))) {
1902 		instrumentation_begin();
1903 		panic("Can't handle #VC exception from unsupported context\n");
1904 		instrumentation_end();
1905 	}
1906 
1907 	/*
1908 	 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1909 	 */
1910 	if (vc_is_db(error_code)) {
1911 		exc_debug(regs);
1912 		return;
1913 	}
1914 
1915 	irq_state = irqentry_nmi_enter(regs);
1916 
1917 	instrumentation_begin();
1918 
1919 	if (!vc_raw_handle_exception(regs, error_code)) {
1920 		/* Show some debug info */
1921 		show_regs(regs);
1922 
1923 		/* Ask hypervisor to sev_es_terminate */
1924 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
1925 
1926 		/* If that fails and we get here - just panic */
1927 		panic("Returned from Terminate-Request to Hypervisor\n");
1928 	}
1929 
1930 	instrumentation_end();
1931 	irqentry_nmi_exit(regs, irq_state);
1932 }
1933 
1934 /*
1935  * Runtime #VC exception handler when raised from user mode. Runs in IRQ mode
1936  * and will kill the current task with SIGBUS when an error happens.
1937  */
1938 DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)
1939 {
1940 	/*
1941 	 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1942 	 */
1943 	if (vc_is_db(error_code)) {
1944 		noist_exc_debug(regs);
1945 		return;
1946 	}
1947 
1948 	irqentry_enter_from_user_mode(regs);
1949 	instrumentation_begin();
1950 
1951 	if (!vc_raw_handle_exception(regs, error_code)) {
1952 		/*
1953 		 * Do not kill the machine if user-space triggered the
1954 		 * exception. Send SIGBUS instead and let user-space deal with
1955 		 * it.
1956 		 */
1957 		force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1958 	}
1959 
1960 	instrumentation_end();
1961 	irqentry_exit_to_user_mode(regs);
1962 }
1963 
1964 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1965 {
1966 	unsigned long exit_code = regs->orig_ax;
1967 	struct es_em_ctxt ctxt;
1968 	enum es_result result;
1969 
1970 	vc_ghcb_invalidate(boot_ghcb);
1971 
1972 	result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1973 	if (result == ES_OK)
1974 		result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1975 
1976 	/* Done - now check the result */
1977 	switch (result) {
1978 	case ES_OK:
1979 		vc_finish_insn(&ctxt);
1980 		break;
1981 	case ES_UNSUPPORTED:
1982 		early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1983 				exit_code, regs->ip);
1984 		goto fail;
1985 	case ES_VMM_ERROR:
1986 		early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1987 				exit_code, regs->ip);
1988 		goto fail;
1989 	case ES_DECODE_FAILED:
1990 		early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1991 				exit_code, regs->ip);
1992 		goto fail;
1993 	case ES_EXCEPTION:
1994 		vc_early_forward_exception(&ctxt);
1995 		break;
1996 	case ES_RETRY:
1997 		/* Nothing to do */
1998 		break;
1999 	default:
2000 		BUG();
2001 	}
2002 
2003 	return true;
2004 
2005 fail:
2006 	show_regs(regs);
2007 
2008 	sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
2009 }
2010 
2011 /*
2012  * Initial set up of SNP relies on information provided by the
2013  * Confidential Computing blob, which can be passed to the kernel
2014  * in the following ways, depending on how it is booted:
2015  *
2016  * - when booted via the boot/decompress kernel:
2017  *   - via boot_params
2018  *
2019  * - when booted directly by firmware/bootloader (e.g. CONFIG_PVH):
2020  *   - via a setup_data entry, as defined by the Linux Boot Protocol
2021  *
2022  * Scan for the blob in that order.
2023  */
2024 static __init struct cc_blob_sev_info *find_cc_blob(struct boot_params *bp)
2025 {
2026 	struct cc_blob_sev_info *cc_info;
2027 
2028 	/* Boot kernel would have passed the CC blob via boot_params. */
2029 	if (bp->cc_blob_address) {
2030 		cc_info = (struct cc_blob_sev_info *)(unsigned long)bp->cc_blob_address;
2031 		goto found_cc_info;
2032 	}
2033 
2034 	/*
2035 	 * If kernel was booted directly, without the use of the
2036 	 * boot/decompression kernel, the CC blob may have been passed via
2037 	 * setup_data instead.
2038 	 */
2039 	cc_info = find_cc_blob_setup_data(bp);
2040 	if (!cc_info)
2041 		return NULL;
2042 
2043 found_cc_info:
2044 	if (cc_info->magic != CC_BLOB_SEV_HDR_MAGIC)
2045 		snp_abort();
2046 
2047 	return cc_info;
2048 }
2049 
2050 bool __init snp_init(struct boot_params *bp)
2051 {
2052 	struct cc_blob_sev_info *cc_info;
2053 
2054 	if (!bp)
2055 		return false;
2056 
2057 	cc_info = find_cc_blob(bp);
2058 	if (!cc_info)
2059 		return false;
2060 
2061 	setup_cpuid_table(cc_info);
2062 
2063 	/*
2064 	 * The CC blob will be used later to access the secrets page. Cache
2065 	 * it here like the boot kernel does.
2066 	 */
2067 	bp->cc_blob_address = (u32)(unsigned long)cc_info;
2068 
2069 	return true;
2070 }
2071 
2072 void __init __noreturn snp_abort(void)
2073 {
2074 	sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
2075 }
2076 
2077 static void dump_cpuid_table(void)
2078 {
2079 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
2080 	int i = 0;
2081 
2082 	pr_info("count=%d reserved=0x%x reserved2=0x%llx\n",
2083 		cpuid_table->count, cpuid_table->__reserved1, cpuid_table->__reserved2);
2084 
2085 	for (i = 0; i < SNP_CPUID_COUNT_MAX; i++) {
2086 		const struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
2087 
2088 		pr_info("index=%3d fn=0x%08x subfn=0x%08x: eax=0x%08x ebx=0x%08x ecx=0x%08x edx=0x%08x xcr0_in=0x%016llx xss_in=0x%016llx reserved=0x%016llx\n",
2089 			i, fn->eax_in, fn->ecx_in, fn->eax, fn->ebx, fn->ecx,
2090 			fn->edx, fn->xcr0_in, fn->xss_in, fn->__reserved);
2091 	}
2092 }
2093 
2094 /*
2095  * It is useful from an auditing/testing perspective to provide an easy way
2096  * for the guest owner to know that the CPUID table has been initialized as
2097  * expected, but that initialization happens too early in boot to print any
2098  * sort of indicator, and there's not really any other good place to do it,
2099  * so do it here.
2100  */
2101 static int __init report_cpuid_table(void)
2102 {
2103 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
2104 
2105 	if (!cpuid_table->count)
2106 		return 0;
2107 
2108 	pr_info("Using SNP CPUID table, %d entries present.\n",
2109 		cpuid_table->count);
2110 
2111 	if (sev_cfg.debug)
2112 		dump_cpuid_table();
2113 
2114 	return 0;
2115 }
2116 arch_initcall(report_cpuid_table);
2117 
2118 static int __init init_sev_config(char *str)
2119 {
2120 	char *s;
2121 
2122 	while ((s = strsep(&str, ","))) {
2123 		if (!strcmp(s, "debug")) {
2124 			sev_cfg.debug = true;
2125 			continue;
2126 		}
2127 
2128 		pr_info("SEV command-line option '%s' was not recognized\n", s);
2129 	}
2130 
2131 	return 1;
2132 }
2133 __setup("sev=", init_sev_config);
2134 
2135 int snp_issue_guest_request(u64 exit_code, struct snp_req_data *input, struct snp_guest_request_ioctl *rio)
2136 {
2137 	struct ghcb_state state;
2138 	struct es_em_ctxt ctxt;
2139 	unsigned long flags;
2140 	struct ghcb *ghcb;
2141 	int ret;
2142 
2143 	rio->exitinfo2 = SEV_RET_NO_FW_CALL;
2144 
2145 	/*
2146 	 * __sev_get_ghcb() needs to run with IRQs disabled because it is using
2147 	 * a per-CPU GHCB.
2148 	 */
2149 	local_irq_save(flags);
2150 
2151 	ghcb = __sev_get_ghcb(&state);
2152 	if (!ghcb) {
2153 		ret = -EIO;
2154 		goto e_restore_irq;
2155 	}
2156 
2157 	vc_ghcb_invalidate(ghcb);
2158 
2159 	if (exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) {
2160 		ghcb_set_rax(ghcb, input->data_gpa);
2161 		ghcb_set_rbx(ghcb, input->data_npages);
2162 	}
2163 
2164 	ret = sev_es_ghcb_hv_call(ghcb, &ctxt, exit_code, input->req_gpa, input->resp_gpa);
2165 	if (ret)
2166 		goto e_put;
2167 
2168 	rio->exitinfo2 = ghcb->save.sw_exit_info_2;
2169 	switch (rio->exitinfo2) {
2170 	case 0:
2171 		break;
2172 
2173 	case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_BUSY):
2174 		ret = -EAGAIN;
2175 		break;
2176 
2177 	case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN):
2178 		/* Number of expected pages are returned in RBX */
2179 		if (exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) {
2180 			input->data_npages = ghcb_get_rbx(ghcb);
2181 			ret = -ENOSPC;
2182 			break;
2183 		}
2184 		fallthrough;
2185 	default:
2186 		ret = -EIO;
2187 		break;
2188 	}
2189 
2190 e_put:
2191 	__sev_put_ghcb(&state);
2192 e_restore_irq:
2193 	local_irq_restore(flags);
2194 
2195 	return ret;
2196 }
2197 EXPORT_SYMBOL_GPL(snp_issue_guest_request);
2198 
2199 static struct platform_device sev_guest_device = {
2200 	.name		= "sev-guest",
2201 	.id		= -1,
2202 };
2203 
2204 static int __init snp_init_platform_device(void)
2205 {
2206 	struct sev_guest_platform_data data;
2207 	u64 gpa;
2208 
2209 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
2210 		return -ENODEV;
2211 
2212 	gpa = get_secrets_page();
2213 	if (!gpa)
2214 		return -ENODEV;
2215 
2216 	data.secrets_gpa = gpa;
2217 	if (platform_device_add_data(&sev_guest_device, &data, sizeof(data)))
2218 		return -ENODEV;
2219 
2220 	if (platform_device_register(&sev_guest_device))
2221 		return -ENODEV;
2222 
2223 	pr_info("SNP guest platform device initialized.\n");
2224 	return 0;
2225 }
2226 device_initcall(snp_init_platform_device);
2227