xref: /linux/arch/x86/coco/sev/core.c (revision 3ee9cebd0a5e7ea47eb35cec95eaa1a866af982d)
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 <linux/dmi.h>
27 #include <uapi/linux/sev-guest.h>
28 #include <crypto/gcm.h>
29 
30 #include <asm/init.h>
31 #include <asm/cpu_entry_area.h>
32 #include <asm/stacktrace.h>
33 #include <asm/sev.h>
34 #include <asm/sev-internal.h>
35 #include <asm/insn-eval.h>
36 #include <asm/fpu/xcr.h>
37 #include <asm/processor.h>
38 #include <asm/realmode.h>
39 #include <asm/setup.h>
40 #include <asm/traps.h>
41 #include <asm/svm.h>
42 #include <asm/smp.h>
43 #include <asm/cpu.h>
44 #include <asm/apic.h>
45 #include <asm/cpuid/api.h>
46 #include <asm/cmdline.h>
47 #include <asm/msr.h>
48 
49 /* AP INIT values as documented in the APM2  section "Processor Initialization State" */
50 #define AP_INIT_CS_LIMIT		0xffff
51 #define AP_INIT_DS_LIMIT		0xffff
52 #define AP_INIT_LDTR_LIMIT		0xffff
53 #define AP_INIT_GDTR_LIMIT		0xffff
54 #define AP_INIT_IDTR_LIMIT		0xffff
55 #define AP_INIT_TR_LIMIT		0xffff
56 #define AP_INIT_RFLAGS_DEFAULT		0x2
57 #define AP_INIT_DR6_DEFAULT		0xffff0ff0
58 #define AP_INIT_GPAT_DEFAULT		0x0007040600070406ULL
59 #define AP_INIT_XCR0_DEFAULT		0x1
60 #define AP_INIT_X87_FTW_DEFAULT		0x5555
61 #define AP_INIT_X87_FCW_DEFAULT		0x0040
62 #define AP_INIT_CR0_DEFAULT		0x60000010
63 #define AP_INIT_MXCSR_DEFAULT		0x1f80
64 
65 static const char * const sev_status_feat_names[] = {
66 	[MSR_AMD64_SEV_ENABLED_BIT]		= "SEV",
67 	[MSR_AMD64_SEV_ES_ENABLED_BIT]		= "SEV-ES",
68 	[MSR_AMD64_SEV_SNP_ENABLED_BIT]		= "SEV-SNP",
69 	[MSR_AMD64_SNP_VTOM_BIT]		= "vTom",
70 	[MSR_AMD64_SNP_REFLECT_VC_BIT]		= "ReflectVC",
71 	[MSR_AMD64_SNP_RESTRICTED_INJ_BIT]	= "RI",
72 	[MSR_AMD64_SNP_ALT_INJ_BIT]		= "AI",
73 	[MSR_AMD64_SNP_DEBUG_SWAP_BIT]		= "DebugSwap",
74 	[MSR_AMD64_SNP_PREVENT_HOST_IBS_BIT]	= "NoHostIBS",
75 	[MSR_AMD64_SNP_BTB_ISOLATION_BIT]	= "BTBIsol",
76 	[MSR_AMD64_SNP_VMPL_SSS_BIT]		= "VmplSSS",
77 	[MSR_AMD64_SNP_SECURE_TSC_BIT]		= "SecureTSC",
78 	[MSR_AMD64_SNP_VMGEXIT_PARAM_BIT]	= "VMGExitParam",
79 	[MSR_AMD64_SNP_IBS_VIRT_BIT]		= "IBSVirt",
80 	[MSR_AMD64_SNP_VMSA_REG_PROT_BIT]	= "VMSARegProt",
81 	[MSR_AMD64_SNP_SMT_PROT_BIT]		= "SMTProt",
82 };
83 
84 /*
85  * For Secure TSC guests, the BSP fetches TSC_INFO using SNP guest messaging and
86  * initializes snp_tsc_scale and snp_tsc_offset. These values are replicated
87  * across the APs VMSA fields (TSC_SCALE and TSC_OFFSET).
88  */
89 static u64 snp_tsc_scale __ro_after_init;
90 static u64 snp_tsc_offset __ro_after_init;
91 static unsigned long snp_tsc_freq_khz __ro_after_init;
92 
93 DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
94 DEFINE_PER_CPU(struct sev_es_save_area *, sev_vmsa);
95 
96 /*
97  * SVSM related information:
98  *   When running under an SVSM, the VMPL that Linux is executing at must be
99  *   non-zero. The VMPL is therefore used to indicate the presence of an SVSM.
100  */
101 u8 snp_vmpl __ro_after_init;
102 EXPORT_SYMBOL_GPL(snp_vmpl);
103 
104 static u64 __init get_snp_jump_table_addr(void)
105 {
106 	struct snp_secrets_page *secrets;
107 	void __iomem *mem;
108 	u64 addr;
109 
110 	mem = ioremap_encrypted(sev_secrets_pa, PAGE_SIZE);
111 	if (!mem) {
112 		pr_err("Unable to locate AP jump table address: failed to map the SNP secrets page.\n");
113 		return 0;
114 	}
115 
116 	secrets = (__force struct snp_secrets_page *)mem;
117 
118 	addr = secrets->os_area.ap_jump_table_pa;
119 	iounmap(mem);
120 
121 	return addr;
122 }
123 
124 static u64 __init get_jump_table_addr(void)
125 {
126 	struct ghcb_state state;
127 	unsigned long flags;
128 	struct ghcb *ghcb;
129 	u64 ret = 0;
130 
131 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
132 		return get_snp_jump_table_addr();
133 
134 	local_irq_save(flags);
135 
136 	ghcb = __sev_get_ghcb(&state);
137 
138 	vc_ghcb_invalidate(ghcb);
139 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
140 	ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
141 	ghcb_set_sw_exit_info_2(ghcb, 0);
142 
143 	sev_es_wr_ghcb_msr(__pa(ghcb));
144 	VMGEXIT();
145 
146 	if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
147 	    ghcb_sw_exit_info_2_is_valid(ghcb))
148 		ret = ghcb->save.sw_exit_info_2;
149 
150 	__sev_put_ghcb(&state);
151 
152 	local_irq_restore(flags);
153 
154 	return ret;
155 }
156 
157 static inline void __pval_terminate(u64 pfn, bool action, unsigned int page_size,
158 				    int ret, u64 svsm_ret)
159 {
160 	WARN(1, "PVALIDATE failure: pfn: 0x%llx, action: %u, size: %u, ret: %d, svsm_ret: 0x%llx\n",
161 	     pfn, action, page_size, ret, svsm_ret);
162 
163 	sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
164 }
165 
166 static void svsm_pval_terminate(struct svsm_pvalidate_call *pc, int ret, u64 svsm_ret)
167 {
168 	unsigned int page_size;
169 	bool action;
170 	u64 pfn;
171 
172 	pfn = pc->entry[pc->cur_index].pfn;
173 	action = pc->entry[pc->cur_index].action;
174 	page_size = pc->entry[pc->cur_index].page_size;
175 
176 	__pval_terminate(pfn, action, page_size, ret, svsm_ret);
177 }
178 
179 static void pval_pages(struct snp_psc_desc *desc)
180 {
181 	struct psc_entry *e;
182 	unsigned long vaddr;
183 	unsigned int size;
184 	unsigned int i;
185 	bool validate;
186 	u64 pfn;
187 	int rc;
188 
189 	for (i = 0; i <= desc->hdr.end_entry; i++) {
190 		e = &desc->entries[i];
191 
192 		pfn = e->gfn;
193 		vaddr = (unsigned long)pfn_to_kaddr(pfn);
194 		size = e->pagesize ? RMP_PG_SIZE_2M : RMP_PG_SIZE_4K;
195 		validate = e->operation == SNP_PAGE_STATE_PRIVATE;
196 
197 		rc = pvalidate(vaddr, size, validate);
198 		if (!rc)
199 			continue;
200 
201 		if (rc == PVALIDATE_FAIL_SIZEMISMATCH && size == RMP_PG_SIZE_2M) {
202 			unsigned long vaddr_end = vaddr + PMD_SIZE;
203 
204 			for (; vaddr < vaddr_end; vaddr += PAGE_SIZE, pfn++) {
205 				rc = pvalidate(vaddr, RMP_PG_SIZE_4K, validate);
206 				if (rc)
207 					__pval_terminate(pfn, validate, RMP_PG_SIZE_4K, rc, 0);
208 			}
209 		} else {
210 			__pval_terminate(pfn, validate, size, rc, 0);
211 		}
212 	}
213 }
214 
215 static u64 svsm_build_ca_from_pfn_range(u64 pfn, u64 pfn_end, bool action,
216 					struct svsm_pvalidate_call *pc)
217 {
218 	struct svsm_pvalidate_entry *pe;
219 
220 	/* Nothing in the CA yet */
221 	pc->num_entries = 0;
222 	pc->cur_index   = 0;
223 
224 	pe = &pc->entry[0];
225 
226 	while (pfn < pfn_end) {
227 		pe->page_size = RMP_PG_SIZE_4K;
228 		pe->action    = action;
229 		pe->ignore_cf = 0;
230 		pe->rsvd      = 0;
231 		pe->pfn       = pfn;
232 
233 		pe++;
234 		pfn++;
235 
236 		pc->num_entries++;
237 		if (pc->num_entries == SVSM_PVALIDATE_MAX_COUNT)
238 			break;
239 	}
240 
241 	return pfn;
242 }
243 
244 static int svsm_build_ca_from_psc_desc(struct snp_psc_desc *desc, unsigned int desc_entry,
245 				       struct svsm_pvalidate_call *pc)
246 {
247 	struct svsm_pvalidate_entry *pe;
248 	struct psc_entry *e;
249 
250 	/* Nothing in the CA yet */
251 	pc->num_entries = 0;
252 	pc->cur_index   = 0;
253 
254 	pe = &pc->entry[0];
255 	e  = &desc->entries[desc_entry];
256 
257 	while (desc_entry <= desc->hdr.end_entry) {
258 		pe->page_size = e->pagesize ? RMP_PG_SIZE_2M : RMP_PG_SIZE_4K;
259 		pe->action    = e->operation == SNP_PAGE_STATE_PRIVATE;
260 		pe->ignore_cf = 0;
261 		pe->rsvd      = 0;
262 		pe->pfn       = e->gfn;
263 
264 		pe++;
265 		e++;
266 
267 		desc_entry++;
268 		pc->num_entries++;
269 		if (pc->num_entries == SVSM_PVALIDATE_MAX_COUNT)
270 			break;
271 	}
272 
273 	return desc_entry;
274 }
275 
276 static void svsm_pval_pages(struct snp_psc_desc *desc)
277 {
278 	struct svsm_pvalidate_entry pv_4k[VMGEXIT_PSC_MAX_ENTRY];
279 	unsigned int i, pv_4k_count = 0;
280 	struct svsm_pvalidate_call *pc;
281 	struct svsm_call call = {};
282 	unsigned long flags;
283 	bool action;
284 	u64 pc_pa;
285 	int ret;
286 
287 	/*
288 	 * This can be called very early in the boot, use native functions in
289 	 * order to avoid paravirt issues.
290 	 */
291 	flags = native_local_irq_save();
292 
293 	/*
294 	 * The SVSM calling area (CA) can support processing 510 entries at a
295 	 * time. Loop through the Page State Change descriptor until the CA is
296 	 * full or the last entry in the descriptor is reached, at which time
297 	 * the SVSM is invoked. This repeats until all entries in the descriptor
298 	 * are processed.
299 	 */
300 	call.caa = svsm_get_caa();
301 
302 	pc = (struct svsm_pvalidate_call *)call.caa->svsm_buffer;
303 	pc_pa = svsm_get_caa_pa() + offsetof(struct svsm_ca, svsm_buffer);
304 
305 	/* Protocol 0, Call ID 1 */
306 	call.rax = SVSM_CORE_CALL(SVSM_CORE_PVALIDATE);
307 	call.rcx = pc_pa;
308 
309 	for (i = 0; i <= desc->hdr.end_entry;) {
310 		i = svsm_build_ca_from_psc_desc(desc, i, pc);
311 
312 		do {
313 			ret = svsm_perform_call_protocol(&call);
314 			if (!ret)
315 				continue;
316 
317 			/*
318 			 * Check if the entry failed because of an RMP mismatch (a
319 			 * PVALIDATE at 2M was requested, but the page is mapped in
320 			 * the RMP as 4K).
321 			 */
322 
323 			if (call.rax_out == SVSM_PVALIDATE_FAIL_SIZEMISMATCH &&
324 			    pc->entry[pc->cur_index].page_size == RMP_PG_SIZE_2M) {
325 				/* Save this entry for post-processing at 4K */
326 				pv_4k[pv_4k_count++] = pc->entry[pc->cur_index];
327 
328 				/* Skip to the next one unless at the end of the list */
329 				pc->cur_index++;
330 				if (pc->cur_index < pc->num_entries)
331 					ret = -EAGAIN;
332 				else
333 					ret = 0;
334 			}
335 		} while (ret == -EAGAIN);
336 
337 		if (ret)
338 			svsm_pval_terminate(pc, ret, call.rax_out);
339 	}
340 
341 	/* Process any entries that failed to be validated at 2M and validate them at 4K */
342 	for (i = 0; i < pv_4k_count; i++) {
343 		u64 pfn, pfn_end;
344 
345 		action  = pv_4k[i].action;
346 		pfn     = pv_4k[i].pfn;
347 		pfn_end = pfn + 512;
348 
349 		while (pfn < pfn_end) {
350 			pfn = svsm_build_ca_from_pfn_range(pfn, pfn_end, action, pc);
351 
352 			ret = svsm_perform_call_protocol(&call);
353 			if (ret)
354 				svsm_pval_terminate(pc, ret, call.rax_out);
355 		}
356 	}
357 
358 	native_local_irq_restore(flags);
359 }
360 
361 static void pvalidate_pages(struct snp_psc_desc *desc)
362 {
363 	if (snp_vmpl)
364 		svsm_pval_pages(desc);
365 	else
366 		pval_pages(desc);
367 }
368 
369 static int vmgexit_psc(struct ghcb *ghcb, struct snp_psc_desc *desc)
370 {
371 	int cur_entry, end_entry, ret = 0;
372 	struct snp_psc_desc *data;
373 	struct es_em_ctxt ctxt;
374 
375 	vc_ghcb_invalidate(ghcb);
376 
377 	/* Copy the input desc into GHCB shared buffer */
378 	data = (struct snp_psc_desc *)ghcb->shared_buffer;
379 	memcpy(ghcb->shared_buffer, desc, min_t(int, GHCB_SHARED_BUF_SIZE, sizeof(*desc)));
380 
381 	/*
382 	 * As per the GHCB specification, the hypervisor can resume the guest
383 	 * before processing all the entries. Check whether all the entries
384 	 * are processed. If not, then keep retrying. Note, the hypervisor
385 	 * will update the data memory directly to indicate the status, so
386 	 * reference the data->hdr everywhere.
387 	 *
388 	 * The strategy here is to wait for the hypervisor to change the page
389 	 * state in the RMP table before guest accesses the memory pages. If the
390 	 * page state change was not successful, then later memory access will
391 	 * result in a crash.
392 	 */
393 	cur_entry = data->hdr.cur_entry;
394 	end_entry = data->hdr.end_entry;
395 
396 	while (data->hdr.cur_entry <= data->hdr.end_entry) {
397 		ghcb_set_sw_scratch(ghcb, (u64)__pa(data));
398 
399 		/* This will advance the shared buffer data points to. */
400 		ret = sev_es_ghcb_hv_call(ghcb, &ctxt, SVM_VMGEXIT_PSC, 0, 0);
401 
402 		/*
403 		 * Page State Change VMGEXIT can pass error code through
404 		 * exit_info_2.
405 		 */
406 		if (WARN(ret || ghcb->save.sw_exit_info_2,
407 			 "SNP: PSC failed ret=%d exit_info_2=%llx\n",
408 			 ret, ghcb->save.sw_exit_info_2)) {
409 			ret = 1;
410 			goto out;
411 		}
412 
413 		/* Verify that reserved bit is not set */
414 		if (WARN(data->hdr.reserved, "Reserved bit is set in the PSC header\n")) {
415 			ret = 1;
416 			goto out;
417 		}
418 
419 		/*
420 		 * Sanity check that entry processing is not going backwards.
421 		 * This will happen only if hypervisor is tricking us.
422 		 */
423 		if (WARN(data->hdr.end_entry > end_entry || cur_entry > data->hdr.cur_entry,
424 "SNP: PSC processing going backward, end_entry %d (got %d) cur_entry %d (got %d)\n",
425 			 end_entry, data->hdr.end_entry, cur_entry, data->hdr.cur_entry)) {
426 			ret = 1;
427 			goto out;
428 		}
429 	}
430 
431 out:
432 	return ret;
433 }
434 
435 static unsigned long __set_pages_state(struct snp_psc_desc *data, unsigned long vaddr,
436 				       unsigned long vaddr_end, int op)
437 {
438 	struct ghcb_state state;
439 	bool use_large_entry;
440 	struct psc_hdr *hdr;
441 	struct psc_entry *e;
442 	unsigned long flags;
443 	unsigned long pfn;
444 	struct ghcb *ghcb;
445 	int i;
446 
447 	hdr = &data->hdr;
448 	e = data->entries;
449 
450 	memset(data, 0, sizeof(*data));
451 	i = 0;
452 
453 	while (vaddr < vaddr_end && i < ARRAY_SIZE(data->entries)) {
454 		hdr->end_entry = i;
455 
456 		if (is_vmalloc_addr((void *)vaddr)) {
457 			pfn = vmalloc_to_pfn((void *)vaddr);
458 			use_large_entry = false;
459 		} else {
460 			pfn = __pa(vaddr) >> PAGE_SHIFT;
461 			use_large_entry = true;
462 		}
463 
464 		e->gfn = pfn;
465 		e->operation = op;
466 
467 		if (use_large_entry && IS_ALIGNED(vaddr, PMD_SIZE) &&
468 		    (vaddr_end - vaddr) >= PMD_SIZE) {
469 			e->pagesize = RMP_PG_SIZE_2M;
470 			vaddr += PMD_SIZE;
471 		} else {
472 			e->pagesize = RMP_PG_SIZE_4K;
473 			vaddr += PAGE_SIZE;
474 		}
475 
476 		e++;
477 		i++;
478 	}
479 
480 	/* Page validation must be rescinded before changing to shared */
481 	if (op == SNP_PAGE_STATE_SHARED)
482 		pvalidate_pages(data);
483 
484 	local_irq_save(flags);
485 
486 	if (sev_cfg.ghcbs_initialized)
487 		ghcb = __sev_get_ghcb(&state);
488 	else
489 		ghcb = boot_ghcb;
490 
491 	/* Invoke the hypervisor to perform the page state changes */
492 	if (!ghcb || vmgexit_psc(ghcb, data))
493 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
494 
495 	if (sev_cfg.ghcbs_initialized)
496 		__sev_put_ghcb(&state);
497 
498 	local_irq_restore(flags);
499 
500 	/* Page validation must be performed after changing to private */
501 	if (op == SNP_PAGE_STATE_PRIVATE)
502 		pvalidate_pages(data);
503 
504 	return vaddr;
505 }
506 
507 static void set_pages_state(unsigned long vaddr, unsigned long npages, int op)
508 {
509 	struct snp_psc_desc desc;
510 	unsigned long vaddr_end;
511 
512 	/* Use the MSR protocol when a GHCB is not available. */
513 	if (!boot_ghcb)
514 		return early_set_pages_state(vaddr, __pa(vaddr), npages, op);
515 
516 	vaddr = vaddr & PAGE_MASK;
517 	vaddr_end = vaddr + (npages << PAGE_SHIFT);
518 
519 	while (vaddr < vaddr_end)
520 		vaddr = __set_pages_state(&desc, vaddr, vaddr_end, op);
521 }
522 
523 void snp_set_memory_shared(unsigned long vaddr, unsigned long npages)
524 {
525 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
526 		return;
527 
528 	set_pages_state(vaddr, npages, SNP_PAGE_STATE_SHARED);
529 }
530 
531 void snp_set_memory_private(unsigned long vaddr, unsigned long npages)
532 {
533 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
534 		return;
535 
536 	set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE);
537 }
538 
539 void snp_accept_memory(phys_addr_t start, phys_addr_t end)
540 {
541 	unsigned long vaddr, npages;
542 
543 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
544 		return;
545 
546 	vaddr = (unsigned long)__va(start);
547 	npages = (end - start) >> PAGE_SHIFT;
548 
549 	set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE);
550 }
551 
552 static int vmgexit_ap_control(u64 event, struct sev_es_save_area *vmsa, u32 apic_id)
553 {
554 	bool create = event != SVM_VMGEXIT_AP_DESTROY;
555 	struct ghcb_state state;
556 	unsigned long flags;
557 	struct ghcb *ghcb;
558 	int ret = 0;
559 
560 	local_irq_save(flags);
561 
562 	ghcb = __sev_get_ghcb(&state);
563 
564 	vc_ghcb_invalidate(ghcb);
565 
566 	if (create)
567 		ghcb_set_rax(ghcb, vmsa->sev_features);
568 
569 	ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_CREATION);
570 	ghcb_set_sw_exit_info_1(ghcb,
571 				((u64)apic_id << 32)	|
572 				((u64)snp_vmpl << 16)	|
573 				event);
574 	ghcb_set_sw_exit_info_2(ghcb, __pa(vmsa));
575 
576 	sev_es_wr_ghcb_msr(__pa(ghcb));
577 	VMGEXIT();
578 
579 	if (!ghcb_sw_exit_info_1_is_valid(ghcb) ||
580 	    lower_32_bits(ghcb->save.sw_exit_info_1)) {
581 		pr_err("SNP AP %s error\n", (create ? "CREATE" : "DESTROY"));
582 		ret = -EINVAL;
583 	}
584 
585 	__sev_put_ghcb(&state);
586 
587 	local_irq_restore(flags);
588 
589 	return ret;
590 }
591 
592 static int snp_set_vmsa(void *va, void *caa, int apic_id, bool make_vmsa)
593 {
594 	int ret;
595 
596 	if (snp_vmpl) {
597 		struct svsm_call call = {};
598 		unsigned long flags;
599 
600 		local_irq_save(flags);
601 
602 		call.caa = this_cpu_read(svsm_caa);
603 		call.rcx = __pa(va);
604 
605 		if (make_vmsa) {
606 			/* Protocol 0, Call ID 2 */
607 			call.rax = SVSM_CORE_CALL(SVSM_CORE_CREATE_VCPU);
608 			call.rdx = __pa(caa);
609 			call.r8  = apic_id;
610 		} else {
611 			/* Protocol 0, Call ID 3 */
612 			call.rax = SVSM_CORE_CALL(SVSM_CORE_DELETE_VCPU);
613 		}
614 
615 		ret = svsm_perform_call_protocol(&call);
616 
617 		local_irq_restore(flags);
618 	} else {
619 		/*
620 		 * If the kernel runs at VMPL0, it can change the VMSA
621 		 * bit for a page using the RMPADJUST instruction.
622 		 * However, for the instruction to succeed it must
623 		 * target the permissions of a lesser privileged (higher
624 		 * numbered) VMPL level, so use VMPL1.
625 		 */
626 		u64 attrs = 1;
627 
628 		if (make_vmsa)
629 			attrs |= RMPADJUST_VMSA_PAGE_BIT;
630 
631 		ret = rmpadjust((unsigned long)va, RMP_PG_SIZE_4K, attrs);
632 	}
633 
634 	return ret;
635 }
636 
637 static void snp_cleanup_vmsa(struct sev_es_save_area *vmsa, int apic_id)
638 {
639 	int err;
640 
641 	err = snp_set_vmsa(vmsa, NULL, apic_id, false);
642 	if (err)
643 		pr_err("clear VMSA page failed (%u), leaking page\n", err);
644 	else
645 		free_page((unsigned long)vmsa);
646 }
647 
648 static void set_pte_enc(pte_t *kpte, int level, void *va)
649 {
650 	struct pte_enc_desc d = {
651 		.kpte	   = kpte,
652 		.pte_level = level,
653 		.va	   = va,
654 		.encrypt   = true
655 	};
656 
657 	prepare_pte_enc(&d);
658 	set_pte_enc_mask(kpte, d.pfn, d.new_pgprot);
659 }
660 
661 static void unshare_all_memory(void)
662 {
663 	unsigned long addr, end, size, ghcb;
664 	struct sev_es_runtime_data *data;
665 	unsigned int npages, level;
666 	bool skipped_addr;
667 	pte_t *pte;
668 	int cpu;
669 
670 	/* Unshare the direct mapping. */
671 	addr = PAGE_OFFSET;
672 	end  = PAGE_OFFSET + get_max_mapped();
673 
674 	while (addr < end) {
675 		pte = lookup_address(addr, &level);
676 		size = page_level_size(level);
677 		npages = size / PAGE_SIZE;
678 		skipped_addr = false;
679 
680 		if (!pte || !pte_decrypted(*pte) || pte_none(*pte)) {
681 			addr += size;
682 			continue;
683 		}
684 
685 		/*
686 		 * Ensure that all the per-CPU GHCBs are made private at the
687 		 * end of the unsharing loop so that the switch to the slower
688 		 * MSR protocol happens last.
689 		 */
690 		for_each_possible_cpu(cpu) {
691 			data = per_cpu(runtime_data, cpu);
692 			ghcb = (unsigned long)&data->ghcb_page;
693 
694 			/* Handle the case of a huge page containing the GHCB page */
695 			if (addr <= ghcb && ghcb < addr + size) {
696 				skipped_addr = true;
697 				break;
698 			}
699 		}
700 
701 		if (!skipped_addr) {
702 			set_pte_enc(pte, level, (void *)addr);
703 			snp_set_memory_private(addr, npages);
704 		}
705 		addr += size;
706 	}
707 
708 	/* Unshare all bss decrypted memory. */
709 	addr = (unsigned long)__start_bss_decrypted;
710 	end  = (unsigned long)__start_bss_decrypted_unused;
711 	npages = (end - addr) >> PAGE_SHIFT;
712 
713 	for (; addr < end; addr += PAGE_SIZE) {
714 		pte = lookup_address(addr, &level);
715 		if (!pte || !pte_decrypted(*pte) || pte_none(*pte))
716 			continue;
717 
718 		set_pte_enc(pte, level, (void *)addr);
719 	}
720 	addr = (unsigned long)__start_bss_decrypted;
721 	snp_set_memory_private(addr, npages);
722 
723 	__flush_tlb_all();
724 }
725 
726 /* Stop new private<->shared conversions */
727 void snp_kexec_begin(void)
728 {
729 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
730 		return;
731 
732 	if (!IS_ENABLED(CONFIG_KEXEC_CORE))
733 		return;
734 
735 	/*
736 	 * Crash kernel ends up here with interrupts disabled: can't wait for
737 	 * conversions to finish.
738 	 *
739 	 * If race happened, just report and proceed.
740 	 */
741 	if (!set_memory_enc_stop_conversion())
742 		pr_warn("Failed to stop shared<->private conversions\n");
743 }
744 
745 /*
746  * Shutdown all APs except the one handling kexec/kdump and clearing
747  * the VMSA tag on AP's VMSA pages as they are not being used as
748  * VMSA page anymore.
749  */
750 static void shutdown_all_aps(void)
751 {
752 	struct sev_es_save_area *vmsa;
753 	int apic_id, this_cpu, cpu;
754 
755 	this_cpu = get_cpu();
756 
757 	/*
758 	 * APs are already in HLT loop when enc_kexec_finish() callback
759 	 * is invoked.
760 	 */
761 	for_each_present_cpu(cpu) {
762 		vmsa = per_cpu(sev_vmsa, cpu);
763 
764 		/*
765 		 * The BSP or offlined APs do not have guest allocated VMSA
766 		 * and there is no need  to clear the VMSA tag for this page.
767 		 */
768 		if (!vmsa)
769 			continue;
770 
771 		/*
772 		 * Cannot clear the VMSA tag for the currently running vCPU.
773 		 */
774 		if (this_cpu == cpu) {
775 			unsigned long pa;
776 			struct page *p;
777 
778 			pa = __pa(vmsa);
779 			/*
780 			 * Mark the VMSA page of the running vCPU as offline
781 			 * so that is excluded and not touched by makedumpfile
782 			 * while generating vmcore during kdump.
783 			 */
784 			p = pfn_to_online_page(pa >> PAGE_SHIFT);
785 			if (p)
786 				__SetPageOffline(p);
787 			continue;
788 		}
789 
790 		apic_id = cpuid_to_apicid[cpu];
791 
792 		/*
793 		 * Issue AP destroy to ensure AP gets kicked out of guest mode
794 		 * to allow using RMPADJUST to remove the VMSA tag on it's
795 		 * VMSA page.
796 		 */
797 		vmgexit_ap_control(SVM_VMGEXIT_AP_DESTROY, vmsa, apic_id);
798 		snp_cleanup_vmsa(vmsa, apic_id);
799 	}
800 
801 	put_cpu();
802 }
803 
804 void snp_kexec_finish(void)
805 {
806 	struct sev_es_runtime_data *data;
807 	unsigned long size, addr;
808 	unsigned int level, cpu;
809 	struct ghcb *ghcb;
810 	pte_t *pte;
811 
812 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
813 		return;
814 
815 	if (!IS_ENABLED(CONFIG_KEXEC_CORE))
816 		return;
817 
818 	shutdown_all_aps();
819 
820 	unshare_all_memory();
821 
822 	/*
823 	 * Switch to using the MSR protocol to change per-CPU GHCBs to
824 	 * private. All the per-CPU GHCBs have been switched back to private,
825 	 * so can't do any more GHCB calls to the hypervisor beyond this point
826 	 * until the kexec'ed kernel starts running.
827 	 */
828 	boot_ghcb = NULL;
829 	sev_cfg.ghcbs_initialized = false;
830 
831 	for_each_possible_cpu(cpu) {
832 		data = per_cpu(runtime_data, cpu);
833 		ghcb = &data->ghcb_page;
834 		pte = lookup_address((unsigned long)ghcb, &level);
835 		size = page_level_size(level);
836 		/* Handle the case of a huge page containing the GHCB page */
837 		addr = (unsigned long)ghcb & page_level_mask(level);
838 		set_pte_enc(pte, level, (void *)addr);
839 		snp_set_memory_private(addr, (size / PAGE_SIZE));
840 	}
841 }
842 
843 #define __ATTR_BASE		(SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK)
844 #define INIT_CS_ATTRIBS		(__ATTR_BASE | SVM_SELECTOR_READ_MASK | SVM_SELECTOR_CODE_MASK)
845 #define INIT_DS_ATTRIBS		(__ATTR_BASE | SVM_SELECTOR_WRITE_MASK)
846 
847 #define INIT_LDTR_ATTRIBS	(SVM_SELECTOR_P_MASK | 2)
848 #define INIT_TR_ATTRIBS		(SVM_SELECTOR_P_MASK | 3)
849 
850 static void *snp_alloc_vmsa_page(int cpu)
851 {
852 	struct page *p;
853 
854 	/*
855 	 * Allocate VMSA page to work around the SNP erratum where the CPU will
856 	 * incorrectly signal an RMP violation #PF if a large page (2MB or 1GB)
857 	 * collides with the RMP entry of VMSA page. The recommended workaround
858 	 * is to not use a large page.
859 	 *
860 	 * Allocate an 8k page which is also 8k-aligned.
861 	 */
862 	p = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL_ACCOUNT | __GFP_ZERO, 1);
863 	if (!p)
864 		return NULL;
865 
866 	split_page(p, 1);
867 
868 	/* Free the first 4k. This page may be 2M/1G aligned and cannot be used. */
869 	__free_page(p);
870 
871 	return page_address(p + 1);
872 }
873 
874 static int wakeup_cpu_via_vmgexit(u32 apic_id, unsigned long start_ip, unsigned int cpu)
875 {
876 	struct sev_es_save_area *cur_vmsa, *vmsa;
877 	struct svsm_ca *caa;
878 	u8 sipi_vector;
879 	int ret;
880 	u64 cr4;
881 
882 	/*
883 	 * The hypervisor SNP feature support check has happened earlier, just check
884 	 * the AP_CREATION one here.
885 	 */
886 	if (!(sev_hv_features & GHCB_HV_FT_SNP_AP_CREATION))
887 		return -EOPNOTSUPP;
888 
889 	/*
890 	 * Verify the desired start IP against the known trampoline start IP
891 	 * to catch any future new trampolines that may be introduced that
892 	 * would require a new protected guest entry point.
893 	 */
894 	if (WARN_ONCE(start_ip != real_mode_header->trampoline_start,
895 		      "Unsupported SNP start_ip: %lx\n", start_ip))
896 		return -EINVAL;
897 
898 	/* Override start_ip with known protected guest start IP */
899 	start_ip = real_mode_header->sev_es_trampoline_start;
900 	cur_vmsa = per_cpu(sev_vmsa, cpu);
901 
902 	/*
903 	 * A new VMSA is created each time because there is no guarantee that
904 	 * the current VMSA is the kernels or that the vCPU is not running. If
905 	 * an attempt was done to use the current VMSA with a running vCPU, a
906 	 * #VMEXIT of that vCPU would wipe out all of the settings being done
907 	 * here.
908 	 */
909 	vmsa = (struct sev_es_save_area *)snp_alloc_vmsa_page(cpu);
910 	if (!vmsa)
911 		return -ENOMEM;
912 
913 	/* If an SVSM is present, the SVSM per-CPU CAA will be !NULL */
914 	caa = per_cpu(svsm_caa, cpu);
915 
916 	/* CR4 should maintain the MCE value */
917 	cr4 = native_read_cr4() & X86_CR4_MCE;
918 
919 	/* Set the CS value based on the start_ip converted to a SIPI vector */
920 	sipi_vector		= (start_ip >> 12);
921 	vmsa->cs.base		= sipi_vector << 12;
922 	vmsa->cs.limit		= AP_INIT_CS_LIMIT;
923 	vmsa->cs.attrib		= INIT_CS_ATTRIBS;
924 	vmsa->cs.selector	= sipi_vector << 8;
925 
926 	/* Set the RIP value based on start_ip */
927 	vmsa->rip		= start_ip & 0xfff;
928 
929 	/* Set AP INIT defaults as documented in the APM */
930 	vmsa->ds.limit		= AP_INIT_DS_LIMIT;
931 	vmsa->ds.attrib		= INIT_DS_ATTRIBS;
932 	vmsa->es		= vmsa->ds;
933 	vmsa->fs		= vmsa->ds;
934 	vmsa->gs		= vmsa->ds;
935 	vmsa->ss		= vmsa->ds;
936 
937 	vmsa->gdtr.limit	= AP_INIT_GDTR_LIMIT;
938 	vmsa->ldtr.limit	= AP_INIT_LDTR_LIMIT;
939 	vmsa->ldtr.attrib	= INIT_LDTR_ATTRIBS;
940 	vmsa->idtr.limit	= AP_INIT_IDTR_LIMIT;
941 	vmsa->tr.limit		= AP_INIT_TR_LIMIT;
942 	vmsa->tr.attrib		= INIT_TR_ATTRIBS;
943 
944 	vmsa->cr4		= cr4;
945 	vmsa->cr0		= AP_INIT_CR0_DEFAULT;
946 	vmsa->dr7		= DR7_RESET_VALUE;
947 	vmsa->dr6		= AP_INIT_DR6_DEFAULT;
948 	vmsa->rflags		= AP_INIT_RFLAGS_DEFAULT;
949 	vmsa->g_pat		= AP_INIT_GPAT_DEFAULT;
950 	vmsa->xcr0		= AP_INIT_XCR0_DEFAULT;
951 	vmsa->mxcsr		= AP_INIT_MXCSR_DEFAULT;
952 	vmsa->x87_ftw		= AP_INIT_X87_FTW_DEFAULT;
953 	vmsa->x87_fcw		= AP_INIT_X87_FCW_DEFAULT;
954 
955 	/* SVME must be set. */
956 	vmsa->efer		= EFER_SVME;
957 
958 	/*
959 	 * Set the SNP-specific fields for this VMSA:
960 	 *   VMPL level
961 	 *   SEV_FEATURES (matches the SEV STATUS MSR right shifted 2 bits)
962 	 */
963 	vmsa->vmpl		= snp_vmpl;
964 	vmsa->sev_features	= sev_status >> 2;
965 
966 	/* Populate AP's TSC scale/offset to get accurate TSC values. */
967 	if (cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC)) {
968 		vmsa->tsc_scale = snp_tsc_scale;
969 		vmsa->tsc_offset = snp_tsc_offset;
970 	}
971 
972 	/* Switch the page over to a VMSA page now that it is initialized */
973 	ret = snp_set_vmsa(vmsa, caa, apic_id, true);
974 	if (ret) {
975 		pr_err("set VMSA page failed (%u)\n", ret);
976 		free_page((unsigned long)vmsa);
977 
978 		return -EINVAL;
979 	}
980 
981 	/* Issue VMGEXIT AP Creation NAE event */
982 	ret = vmgexit_ap_control(SVM_VMGEXIT_AP_CREATE, vmsa, apic_id);
983 	if (ret) {
984 		snp_cleanup_vmsa(vmsa, apic_id);
985 		vmsa = NULL;
986 	}
987 
988 	/* Free up any previous VMSA page */
989 	if (cur_vmsa)
990 		snp_cleanup_vmsa(cur_vmsa, apic_id);
991 
992 	/* Record the current VMSA page */
993 	per_cpu(sev_vmsa, cpu) = vmsa;
994 
995 	return ret;
996 }
997 
998 void __init snp_set_wakeup_secondary_cpu(void)
999 {
1000 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1001 		return;
1002 
1003 	/*
1004 	 * Always set this override if SNP is enabled. This makes it the
1005 	 * required method to start APs under SNP. If the hypervisor does
1006 	 * not support AP creation, then no APs will be started.
1007 	 */
1008 	apic_update_callback(wakeup_secondary_cpu, wakeup_cpu_via_vmgexit);
1009 }
1010 
1011 int __init sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
1012 {
1013 	u16 startup_cs, startup_ip;
1014 	phys_addr_t jump_table_pa;
1015 	u64 jump_table_addr;
1016 	u16 __iomem *jump_table;
1017 
1018 	jump_table_addr = get_jump_table_addr();
1019 
1020 	/* On UP guests there is no jump table so this is not a failure */
1021 	if (!jump_table_addr)
1022 		return 0;
1023 
1024 	/* Check if AP Jump Table is page-aligned */
1025 	if (jump_table_addr & ~PAGE_MASK)
1026 		return -EINVAL;
1027 
1028 	jump_table_pa = jump_table_addr & PAGE_MASK;
1029 
1030 	startup_cs = (u16)(rmh->trampoline_start >> 4);
1031 	startup_ip = (u16)(rmh->sev_es_trampoline_start -
1032 			   rmh->trampoline_start);
1033 
1034 	jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
1035 	if (!jump_table)
1036 		return -EIO;
1037 
1038 	writew(startup_ip, &jump_table[0]);
1039 	writew(startup_cs, &jump_table[1]);
1040 
1041 	iounmap(jump_table);
1042 
1043 	return 0;
1044 }
1045 
1046 /*
1047  * This is needed by the OVMF UEFI firmware which will use whatever it finds in
1048  * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
1049  * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
1050  *
1051  * When running under SVSM the CA page is needed too, so map it as well.
1052  */
1053 int __init sev_es_efi_map_ghcbs_cas(pgd_t *pgd)
1054 {
1055 	unsigned long address, pflags, pflags_enc;
1056 	struct sev_es_runtime_data *data;
1057 	int cpu;
1058 	u64 pfn;
1059 
1060 	if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1061 		return 0;
1062 
1063 	pflags = _PAGE_NX | _PAGE_RW;
1064 	pflags_enc = cc_mkenc(pflags);
1065 
1066 	for_each_possible_cpu(cpu) {
1067 		data = per_cpu(runtime_data, cpu);
1068 
1069 		address = __pa(&data->ghcb_page);
1070 		pfn = address >> PAGE_SHIFT;
1071 
1072 		if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
1073 			return 1;
1074 
1075 		if (snp_vmpl) {
1076 			address = per_cpu(svsm_caa_pa, cpu);
1077 			if (!address)
1078 				return 1;
1079 
1080 			pfn = address >> PAGE_SHIFT;
1081 			if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags_enc))
1082 				return 1;
1083 		}
1084 	}
1085 
1086 	return 0;
1087 }
1088 
1089 static void snp_register_per_cpu_ghcb(void)
1090 {
1091 	struct sev_es_runtime_data *data;
1092 	struct ghcb *ghcb;
1093 
1094 	data = this_cpu_read(runtime_data);
1095 	ghcb = &data->ghcb_page;
1096 
1097 	snp_register_ghcb_early(__pa(ghcb));
1098 }
1099 
1100 void setup_ghcb(void)
1101 {
1102 	if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1103 		return;
1104 
1105 	/*
1106 	 * Check whether the runtime #VC exception handler is active. It uses
1107 	 * the per-CPU GHCB page which is set up by sev_es_init_vc_handling().
1108 	 *
1109 	 * If SNP is active, register the per-CPU GHCB page so that the runtime
1110 	 * exception handler can use it.
1111 	 */
1112 	if (initial_vc_handler == (unsigned long)kernel_exc_vmm_communication) {
1113 		if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1114 			snp_register_per_cpu_ghcb();
1115 
1116 		sev_cfg.ghcbs_initialized = true;
1117 
1118 		return;
1119 	}
1120 
1121 	/*
1122 	 * Make sure the hypervisor talks a supported protocol.
1123 	 * This gets called only in the BSP boot phase.
1124 	 */
1125 	if (!sev_es_negotiate_protocol())
1126 		sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
1127 
1128 	/*
1129 	 * Clear the boot_ghcb. The first exception comes in before the bss
1130 	 * section is cleared.
1131 	 */
1132 	memset(&boot_ghcb_page, 0, PAGE_SIZE);
1133 
1134 	/* Alright - Make the boot-ghcb public */
1135 	boot_ghcb = &boot_ghcb_page;
1136 
1137 	/* SNP guest requires that GHCB GPA must be registered. */
1138 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1139 		snp_register_ghcb_early(__pa(&boot_ghcb_page));
1140 }
1141 
1142 #ifdef CONFIG_HOTPLUG_CPU
1143 static void sev_es_ap_hlt_loop(void)
1144 {
1145 	struct ghcb_state state;
1146 	struct ghcb *ghcb;
1147 
1148 	ghcb = __sev_get_ghcb(&state);
1149 
1150 	while (true) {
1151 		vc_ghcb_invalidate(ghcb);
1152 		ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
1153 		ghcb_set_sw_exit_info_1(ghcb, 0);
1154 		ghcb_set_sw_exit_info_2(ghcb, 0);
1155 
1156 		sev_es_wr_ghcb_msr(__pa(ghcb));
1157 		VMGEXIT();
1158 
1159 		/* Wakeup signal? */
1160 		if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
1161 		    ghcb->save.sw_exit_info_2)
1162 			break;
1163 	}
1164 
1165 	__sev_put_ghcb(&state);
1166 }
1167 
1168 /*
1169  * Play_dead handler when running under SEV-ES. This is needed because
1170  * the hypervisor can't deliver an SIPI request to restart the AP.
1171  * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
1172  * hypervisor wakes it up again.
1173  */
1174 static void sev_es_play_dead(void)
1175 {
1176 	play_dead_common();
1177 
1178 	/* IRQs now disabled */
1179 
1180 	sev_es_ap_hlt_loop();
1181 
1182 	/*
1183 	 * If we get here, the VCPU was woken up again. Jump to CPU
1184 	 * startup code to get it back online.
1185 	 */
1186 	soft_restart_cpu();
1187 }
1188 #else  /* CONFIG_HOTPLUG_CPU */
1189 #define sev_es_play_dead	native_play_dead
1190 #endif /* CONFIG_HOTPLUG_CPU */
1191 
1192 #ifdef CONFIG_SMP
1193 static void __init sev_es_setup_play_dead(void)
1194 {
1195 	smp_ops.play_dead = sev_es_play_dead;
1196 }
1197 #else
1198 static inline void sev_es_setup_play_dead(void) { }
1199 #endif
1200 
1201 static void __init alloc_runtime_data(int cpu)
1202 {
1203 	struct sev_es_runtime_data *data;
1204 
1205 	data = memblock_alloc_node(sizeof(*data), PAGE_SIZE, cpu_to_node(cpu));
1206 	if (!data)
1207 		panic("Can't allocate SEV-ES runtime data");
1208 
1209 	per_cpu(runtime_data, cpu) = data;
1210 
1211 	if (snp_vmpl) {
1212 		struct svsm_ca *caa;
1213 
1214 		/* Allocate the SVSM CA page if an SVSM is present */
1215 		caa = memblock_alloc_or_panic(sizeof(*caa), PAGE_SIZE);
1216 
1217 		per_cpu(svsm_caa, cpu) = caa;
1218 		per_cpu(svsm_caa_pa, cpu) = __pa(caa);
1219 	}
1220 }
1221 
1222 static void __init init_ghcb(int cpu)
1223 {
1224 	struct sev_es_runtime_data *data;
1225 	int err;
1226 
1227 	data = per_cpu(runtime_data, cpu);
1228 
1229 	err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
1230 					 sizeof(data->ghcb_page));
1231 	if (err)
1232 		panic("Can't map GHCBs unencrypted");
1233 
1234 	memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
1235 
1236 	data->ghcb_active = false;
1237 	data->backup_ghcb_active = false;
1238 }
1239 
1240 void __init sev_es_init_vc_handling(void)
1241 {
1242 	int cpu;
1243 
1244 	BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
1245 
1246 	if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1247 		return;
1248 
1249 	if (!sev_es_check_cpu_features())
1250 		panic("SEV-ES CPU Features missing");
1251 
1252 	/*
1253 	 * SNP is supported in v2 of the GHCB spec which mandates support for HV
1254 	 * features.
1255 	 */
1256 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) {
1257 		sev_hv_features = get_hv_features();
1258 
1259 		if (!(sev_hv_features & GHCB_HV_FT_SNP))
1260 			sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
1261 	}
1262 
1263 	/* Initialize per-cpu GHCB pages */
1264 	for_each_possible_cpu(cpu) {
1265 		alloc_runtime_data(cpu);
1266 		init_ghcb(cpu);
1267 	}
1268 
1269 	/* If running under an SVSM, switch to the per-cpu CA */
1270 	if (snp_vmpl) {
1271 		struct svsm_call call = {};
1272 		unsigned long flags;
1273 		int ret;
1274 
1275 		local_irq_save(flags);
1276 
1277 		/*
1278 		 * SVSM_CORE_REMAP_CA call:
1279 		 *   RAX = 0 (Protocol=0, CallID=0)
1280 		 *   RCX = New CA GPA
1281 		 */
1282 		call.caa = svsm_get_caa();
1283 		call.rax = SVSM_CORE_CALL(SVSM_CORE_REMAP_CA);
1284 		call.rcx = this_cpu_read(svsm_caa_pa);
1285 		ret = svsm_perform_call_protocol(&call);
1286 		if (ret)
1287 			panic("Can't remap the SVSM CA, ret=%d, rax_out=0x%llx\n",
1288 			      ret, call.rax_out);
1289 
1290 		sev_cfg.use_cas = true;
1291 
1292 		local_irq_restore(flags);
1293 	}
1294 
1295 	sev_es_setup_play_dead();
1296 
1297 	/* Secondary CPUs use the runtime #VC handler */
1298 	initial_vc_handler = (unsigned long)kernel_exc_vmm_communication;
1299 }
1300 
1301 /*
1302  * SEV-SNP guests should only execute dmi_setup() if EFI_CONFIG_TABLES are
1303  * enabled, as the alternative (fallback) logic for DMI probing in the legacy
1304  * ROM region can cause a crash since this region is not pre-validated.
1305  */
1306 void __init snp_dmi_setup(void)
1307 {
1308 	if (efi_enabled(EFI_CONFIG_TABLES))
1309 		dmi_setup();
1310 }
1311 
1312 static void dump_cpuid_table(void)
1313 {
1314 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
1315 	int i = 0;
1316 
1317 	pr_info("count=%d reserved=0x%x reserved2=0x%llx\n",
1318 		cpuid_table->count, cpuid_table->__reserved1, cpuid_table->__reserved2);
1319 
1320 	for (i = 0; i < SNP_CPUID_COUNT_MAX; i++) {
1321 		const struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
1322 
1323 		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",
1324 			i, fn->eax_in, fn->ecx_in, fn->eax, fn->ebx, fn->ecx,
1325 			fn->edx, fn->xcr0_in, fn->xss_in, fn->__reserved);
1326 	}
1327 }
1328 
1329 /*
1330  * It is useful from an auditing/testing perspective to provide an easy way
1331  * for the guest owner to know that the CPUID table has been initialized as
1332  * expected, but that initialization happens too early in boot to print any
1333  * sort of indicator, and there's not really any other good place to do it,
1334  * so do it here.
1335  *
1336  * If running as an SNP guest, report the current VM privilege level (VMPL).
1337  */
1338 static int __init report_snp_info(void)
1339 {
1340 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
1341 
1342 	if (cpuid_table->count) {
1343 		pr_info("Using SNP CPUID table, %d entries present.\n",
1344 			cpuid_table->count);
1345 
1346 		if (sev_cfg.debug)
1347 			dump_cpuid_table();
1348 	}
1349 
1350 	if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1351 		pr_info("SNP running at VMPL%u.\n", snp_vmpl);
1352 
1353 	return 0;
1354 }
1355 arch_initcall(report_snp_info);
1356 
1357 static void update_attest_input(struct svsm_call *call, struct svsm_attest_call *input)
1358 {
1359 	/* If (new) lengths have been returned, propagate them up */
1360 	if (call->rcx_out != call->rcx)
1361 		input->manifest_buf.len = call->rcx_out;
1362 
1363 	if (call->rdx_out != call->rdx)
1364 		input->certificates_buf.len = call->rdx_out;
1365 
1366 	if (call->r8_out != call->r8)
1367 		input->report_buf.len = call->r8_out;
1368 }
1369 
1370 int snp_issue_svsm_attest_req(u64 call_id, struct svsm_call *call,
1371 			      struct svsm_attest_call *input)
1372 {
1373 	struct svsm_attest_call *ac;
1374 	unsigned long flags;
1375 	u64 attest_call_pa;
1376 	int ret;
1377 
1378 	if (!snp_vmpl)
1379 		return -EINVAL;
1380 
1381 	local_irq_save(flags);
1382 
1383 	call->caa = svsm_get_caa();
1384 
1385 	ac = (struct svsm_attest_call *)call->caa->svsm_buffer;
1386 	attest_call_pa = svsm_get_caa_pa() + offsetof(struct svsm_ca, svsm_buffer);
1387 
1388 	*ac = *input;
1389 
1390 	/*
1391 	 * Set input registers for the request and set RDX and R8 to known
1392 	 * values in order to detect length values being returned in them.
1393 	 */
1394 	call->rax = call_id;
1395 	call->rcx = attest_call_pa;
1396 	call->rdx = -1;
1397 	call->r8 = -1;
1398 	ret = svsm_perform_call_protocol(call);
1399 	update_attest_input(call, input);
1400 
1401 	local_irq_restore(flags);
1402 
1403 	return ret;
1404 }
1405 EXPORT_SYMBOL_GPL(snp_issue_svsm_attest_req);
1406 
1407 static int snp_issue_guest_request(struct snp_guest_req *req)
1408 {
1409 	struct snp_req_data *input = &req->input;
1410 	struct ghcb_state state;
1411 	struct es_em_ctxt ctxt;
1412 	unsigned long flags;
1413 	struct ghcb *ghcb;
1414 	int ret;
1415 
1416 	req->exitinfo2 = SEV_RET_NO_FW_CALL;
1417 
1418 	/*
1419 	 * __sev_get_ghcb() needs to run with IRQs disabled because it is using
1420 	 * a per-CPU GHCB.
1421 	 */
1422 	local_irq_save(flags);
1423 
1424 	ghcb = __sev_get_ghcb(&state);
1425 	if (!ghcb) {
1426 		ret = -EIO;
1427 		goto e_restore_irq;
1428 	}
1429 
1430 	vc_ghcb_invalidate(ghcb);
1431 
1432 	if (req->exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) {
1433 		ghcb_set_rax(ghcb, input->data_gpa);
1434 		ghcb_set_rbx(ghcb, input->data_npages);
1435 	}
1436 
1437 	ret = sev_es_ghcb_hv_call(ghcb, &ctxt, req->exit_code, input->req_gpa, input->resp_gpa);
1438 	if (ret)
1439 		goto e_put;
1440 
1441 	req->exitinfo2 = ghcb->save.sw_exit_info_2;
1442 	switch (req->exitinfo2) {
1443 	case 0:
1444 		break;
1445 
1446 	case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_BUSY):
1447 		ret = -EAGAIN;
1448 		break;
1449 
1450 	case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN):
1451 		/* Number of expected pages are returned in RBX */
1452 		if (req->exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) {
1453 			input->data_npages = ghcb_get_rbx(ghcb);
1454 			ret = -ENOSPC;
1455 			break;
1456 		}
1457 		fallthrough;
1458 	default:
1459 		ret = -EIO;
1460 		break;
1461 	}
1462 
1463 e_put:
1464 	__sev_put_ghcb(&state);
1465 e_restore_irq:
1466 	local_irq_restore(flags);
1467 
1468 	return ret;
1469 }
1470 
1471 /**
1472  * snp_svsm_vtpm_probe() - Probe if SVSM provides a vTPM device
1473  *
1474  * Check that there is SVSM and that it supports at least TPM_SEND_COMMAND
1475  * which is the only request used so far.
1476  *
1477  * Return: true if the platform provides a vTPM SVSM device, false otherwise.
1478  */
1479 static bool snp_svsm_vtpm_probe(void)
1480 {
1481 	struct svsm_call call = {};
1482 
1483 	/* The vTPM device is available only if a SVSM is present */
1484 	if (!snp_vmpl)
1485 		return false;
1486 
1487 	call.caa = svsm_get_caa();
1488 	call.rax = SVSM_VTPM_CALL(SVSM_VTPM_QUERY);
1489 
1490 	if (svsm_perform_call_protocol(&call))
1491 		return false;
1492 
1493 	/* Check platform commands contains TPM_SEND_COMMAND - platform command 8 */
1494 	return call.rcx_out & BIT_ULL(8);
1495 }
1496 
1497 /**
1498  * snp_svsm_vtpm_send_command() - Execute a vTPM operation on SVSM
1499  * @buffer: A buffer used to both send the command and receive the response.
1500  *
1501  * Execute a SVSM_VTPM_CMD call as defined by
1502  * "Secure VM Service Module for SEV-SNP Guests" Publication # 58019 Revision: 1.00
1503  *
1504  * All command request/response buffers have a common structure as specified by
1505  * the following table:
1506  *     Byte      Size       In/Out    Description
1507  *     Offset    (Bytes)
1508  *     0x000     4          In        Platform command
1509  *                          Out       Platform command response size
1510  *
1511  * Each command can build upon this common request/response structure to create
1512  * a structure specific to the command. See include/linux/tpm_svsm.h for more
1513  * details.
1514  *
1515  * Return: 0 on success, -errno on failure
1516  */
1517 int snp_svsm_vtpm_send_command(u8 *buffer)
1518 {
1519 	struct svsm_call call = {};
1520 
1521 	call.caa = svsm_get_caa();
1522 	call.rax = SVSM_VTPM_CALL(SVSM_VTPM_CMD);
1523 	call.rcx = __pa(buffer);
1524 
1525 	return svsm_perform_call_protocol(&call);
1526 }
1527 EXPORT_SYMBOL_GPL(snp_svsm_vtpm_send_command);
1528 
1529 static struct platform_device sev_guest_device = {
1530 	.name		= "sev-guest",
1531 	.id		= -1,
1532 };
1533 
1534 static struct platform_device tpm_svsm_device = {
1535 	.name		= "tpm-svsm",
1536 	.id		= -1,
1537 };
1538 
1539 static int __init snp_init_platform_device(void)
1540 {
1541 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1542 		return -ENODEV;
1543 
1544 	if (platform_device_register(&sev_guest_device))
1545 		return -ENODEV;
1546 
1547 	if (snp_svsm_vtpm_probe() &&
1548 	    platform_device_register(&tpm_svsm_device))
1549 		return -ENODEV;
1550 
1551 	pr_info("SNP guest platform devices initialized.\n");
1552 	return 0;
1553 }
1554 device_initcall(snp_init_platform_device);
1555 
1556 void sev_show_status(void)
1557 {
1558 	int i;
1559 
1560 	pr_info("Status: ");
1561 	for (i = 0; i < MSR_AMD64_SNP_RESV_BIT; i++) {
1562 		if (sev_status & BIT_ULL(i)) {
1563 			if (!sev_status_feat_names[i])
1564 				continue;
1565 
1566 			pr_cont("%s ", sev_status_feat_names[i]);
1567 		}
1568 	}
1569 	pr_cont("\n");
1570 }
1571 
1572 void __init snp_update_svsm_ca(void)
1573 {
1574 	if (!snp_vmpl)
1575 		return;
1576 
1577 	/* Update the CAA to a proper kernel address */
1578 	boot_svsm_caa = &boot_svsm_ca_page;
1579 }
1580 
1581 #ifdef CONFIG_SYSFS
1582 static ssize_t vmpl_show(struct kobject *kobj,
1583 			 struct kobj_attribute *attr, char *buf)
1584 {
1585 	return sysfs_emit(buf, "%d\n", snp_vmpl);
1586 }
1587 
1588 static struct kobj_attribute vmpl_attr = __ATTR_RO(vmpl);
1589 
1590 static struct attribute *vmpl_attrs[] = {
1591 	&vmpl_attr.attr,
1592 	NULL
1593 };
1594 
1595 static struct attribute_group sev_attr_group = {
1596 	.attrs = vmpl_attrs,
1597 };
1598 
1599 static int __init sev_sysfs_init(void)
1600 {
1601 	struct kobject *sev_kobj;
1602 	struct device *dev_root;
1603 	int ret;
1604 
1605 	if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1606 		return -ENODEV;
1607 
1608 	dev_root = bus_get_dev_root(&cpu_subsys);
1609 	if (!dev_root)
1610 		return -ENODEV;
1611 
1612 	sev_kobj = kobject_create_and_add("sev", &dev_root->kobj);
1613 	put_device(dev_root);
1614 
1615 	if (!sev_kobj)
1616 		return -ENOMEM;
1617 
1618 	ret = sysfs_create_group(sev_kobj, &sev_attr_group);
1619 	if (ret)
1620 		kobject_put(sev_kobj);
1621 
1622 	return ret;
1623 }
1624 arch_initcall(sev_sysfs_init);
1625 #endif // CONFIG_SYSFS
1626 
1627 static void free_shared_pages(void *buf, size_t sz)
1628 {
1629 	unsigned int npages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
1630 	int ret;
1631 
1632 	if (!buf)
1633 		return;
1634 
1635 	ret = set_memory_encrypted((unsigned long)buf, npages);
1636 	if (ret) {
1637 		WARN_ONCE(ret, "failed to restore encryption mask (leak it)\n");
1638 		return;
1639 	}
1640 
1641 	__free_pages(virt_to_page(buf), get_order(sz));
1642 }
1643 
1644 static void *alloc_shared_pages(size_t sz)
1645 {
1646 	unsigned int npages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
1647 	struct page *page;
1648 	int ret;
1649 
1650 	page = alloc_pages(GFP_KERNEL_ACCOUNT, get_order(sz));
1651 	if (!page)
1652 		return NULL;
1653 
1654 	ret = set_memory_decrypted((unsigned long)page_address(page), npages);
1655 	if (ret) {
1656 		pr_err("failed to mark page shared, ret=%d\n", ret);
1657 		__free_pages(page, get_order(sz));
1658 		return NULL;
1659 	}
1660 
1661 	return page_address(page);
1662 }
1663 
1664 static u8 *get_vmpck(int id, struct snp_secrets_page *secrets, u32 **seqno)
1665 {
1666 	u8 *key = NULL;
1667 
1668 	switch (id) {
1669 	case 0:
1670 		*seqno = &secrets->os_area.msg_seqno_0;
1671 		key = secrets->vmpck0;
1672 		break;
1673 	case 1:
1674 		*seqno = &secrets->os_area.msg_seqno_1;
1675 		key = secrets->vmpck1;
1676 		break;
1677 	case 2:
1678 		*seqno = &secrets->os_area.msg_seqno_2;
1679 		key = secrets->vmpck2;
1680 		break;
1681 	case 3:
1682 		*seqno = &secrets->os_area.msg_seqno_3;
1683 		key = secrets->vmpck3;
1684 		break;
1685 	default:
1686 		break;
1687 	}
1688 
1689 	return key;
1690 }
1691 
1692 static struct aesgcm_ctx *snp_init_crypto(u8 *key, size_t keylen)
1693 {
1694 	struct aesgcm_ctx *ctx;
1695 
1696 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1697 	if (!ctx)
1698 		return NULL;
1699 
1700 	if (aesgcm_expandkey(ctx, key, keylen, AUTHTAG_LEN)) {
1701 		pr_err("Crypto context initialization failed\n");
1702 		kfree(ctx);
1703 		return NULL;
1704 	}
1705 
1706 	return ctx;
1707 }
1708 
1709 int snp_msg_init(struct snp_msg_desc *mdesc, int vmpck_id)
1710 {
1711 	/* Adjust the default VMPCK key based on the executing VMPL level */
1712 	if (vmpck_id == -1)
1713 		vmpck_id = snp_vmpl;
1714 
1715 	mdesc->vmpck = get_vmpck(vmpck_id, mdesc->secrets, &mdesc->os_area_msg_seqno);
1716 	if (!mdesc->vmpck) {
1717 		pr_err("Invalid VMPCK%d communication key\n", vmpck_id);
1718 		return -EINVAL;
1719 	}
1720 
1721 	/* Verify that VMPCK is not zero. */
1722 	if (!memchr_inv(mdesc->vmpck, 0, VMPCK_KEY_LEN)) {
1723 		pr_err("Empty VMPCK%d communication key\n", vmpck_id);
1724 		return -EINVAL;
1725 	}
1726 
1727 	mdesc->vmpck_id = vmpck_id;
1728 
1729 	mdesc->ctx = snp_init_crypto(mdesc->vmpck, VMPCK_KEY_LEN);
1730 	if (!mdesc->ctx)
1731 		return -ENOMEM;
1732 
1733 	return 0;
1734 }
1735 EXPORT_SYMBOL_GPL(snp_msg_init);
1736 
1737 struct snp_msg_desc *snp_msg_alloc(void)
1738 {
1739 	struct snp_msg_desc *mdesc;
1740 	void __iomem *mem;
1741 
1742 	BUILD_BUG_ON(sizeof(struct snp_guest_msg) > PAGE_SIZE);
1743 
1744 	mdesc = kzalloc(sizeof(struct snp_msg_desc), GFP_KERNEL);
1745 	if (!mdesc)
1746 		return ERR_PTR(-ENOMEM);
1747 
1748 	mem = ioremap_encrypted(sev_secrets_pa, PAGE_SIZE);
1749 	if (!mem)
1750 		goto e_free_mdesc;
1751 
1752 	mdesc->secrets = (__force struct snp_secrets_page *)mem;
1753 
1754 	/* Allocate the shared page used for the request and response message. */
1755 	mdesc->request = alloc_shared_pages(sizeof(struct snp_guest_msg));
1756 	if (!mdesc->request)
1757 		goto e_unmap;
1758 
1759 	mdesc->response = alloc_shared_pages(sizeof(struct snp_guest_msg));
1760 	if (!mdesc->response)
1761 		goto e_free_request;
1762 
1763 	return mdesc;
1764 
1765 e_free_request:
1766 	free_shared_pages(mdesc->request, sizeof(struct snp_guest_msg));
1767 e_unmap:
1768 	iounmap(mem);
1769 e_free_mdesc:
1770 	kfree(mdesc);
1771 
1772 	return ERR_PTR(-ENOMEM);
1773 }
1774 EXPORT_SYMBOL_GPL(snp_msg_alloc);
1775 
1776 void snp_msg_free(struct snp_msg_desc *mdesc)
1777 {
1778 	if (!mdesc)
1779 		return;
1780 
1781 	kfree(mdesc->ctx);
1782 	free_shared_pages(mdesc->response, sizeof(struct snp_guest_msg));
1783 	free_shared_pages(mdesc->request, sizeof(struct snp_guest_msg));
1784 	iounmap((__force void __iomem *)mdesc->secrets);
1785 
1786 	memset(mdesc, 0, sizeof(*mdesc));
1787 	kfree(mdesc);
1788 }
1789 EXPORT_SYMBOL_GPL(snp_msg_free);
1790 
1791 /* Mutex to serialize the shared buffer access and command handling. */
1792 static DEFINE_MUTEX(snp_cmd_mutex);
1793 
1794 /*
1795  * If an error is received from the host or AMD Secure Processor (ASP) there
1796  * are two options. Either retry the exact same encrypted request or discontinue
1797  * using the VMPCK.
1798  *
1799  * This is because in the current encryption scheme GHCB v2 uses AES-GCM to
1800  * encrypt the requests. The IV for this scheme is the sequence number. GCM
1801  * cannot tolerate IV reuse.
1802  *
1803  * The ASP FW v1.51 only increments the sequence numbers on a successful
1804  * guest<->ASP back and forth and only accepts messages at its exact sequence
1805  * number.
1806  *
1807  * So if the sequence number were to be reused the encryption scheme is
1808  * vulnerable. If the sequence number were incremented for a fresh IV the ASP
1809  * will reject the request.
1810  */
1811 static void snp_disable_vmpck(struct snp_msg_desc *mdesc)
1812 {
1813 	pr_alert("Disabling VMPCK%d communication key to prevent IV reuse.\n",
1814 		  mdesc->vmpck_id);
1815 	memzero_explicit(mdesc->vmpck, VMPCK_KEY_LEN);
1816 	mdesc->vmpck = NULL;
1817 }
1818 
1819 static inline u64 __snp_get_msg_seqno(struct snp_msg_desc *mdesc)
1820 {
1821 	u64 count;
1822 
1823 	lockdep_assert_held(&snp_cmd_mutex);
1824 
1825 	/* Read the current message sequence counter from secrets pages */
1826 	count = *mdesc->os_area_msg_seqno;
1827 
1828 	return count + 1;
1829 }
1830 
1831 /* Return a non-zero on success */
1832 static u64 snp_get_msg_seqno(struct snp_msg_desc *mdesc)
1833 {
1834 	u64 count = __snp_get_msg_seqno(mdesc);
1835 
1836 	/*
1837 	 * The message sequence counter for the SNP guest request is a  64-bit
1838 	 * value but the version 2 of GHCB specification defines a 32-bit storage
1839 	 * for it. If the counter exceeds the 32-bit value then return zero.
1840 	 * The caller should check the return value, but if the caller happens to
1841 	 * not check the value and use it, then the firmware treats zero as an
1842 	 * invalid number and will fail the  message request.
1843 	 */
1844 	if (count >= UINT_MAX) {
1845 		pr_err("request message sequence counter overflow\n");
1846 		return 0;
1847 	}
1848 
1849 	return count;
1850 }
1851 
1852 static void snp_inc_msg_seqno(struct snp_msg_desc *mdesc)
1853 {
1854 	/*
1855 	 * The counter is also incremented by the PSP, so increment it by 2
1856 	 * and save in secrets page.
1857 	 */
1858 	*mdesc->os_area_msg_seqno += 2;
1859 }
1860 
1861 static int verify_and_dec_payload(struct snp_msg_desc *mdesc, struct snp_guest_req *req)
1862 {
1863 	struct snp_guest_msg *resp_msg = &mdesc->secret_response;
1864 	struct snp_guest_msg *req_msg = &mdesc->secret_request;
1865 	struct snp_guest_msg_hdr *req_msg_hdr = &req_msg->hdr;
1866 	struct snp_guest_msg_hdr *resp_msg_hdr = &resp_msg->hdr;
1867 	struct aesgcm_ctx *ctx = mdesc->ctx;
1868 	u8 iv[GCM_AES_IV_SIZE] = {};
1869 
1870 	pr_debug("response [seqno %lld type %d version %d sz %d]\n",
1871 		 resp_msg_hdr->msg_seqno, resp_msg_hdr->msg_type, resp_msg_hdr->msg_version,
1872 		 resp_msg_hdr->msg_sz);
1873 
1874 	/* Copy response from shared memory to encrypted memory. */
1875 	memcpy(resp_msg, mdesc->response, sizeof(*resp_msg));
1876 
1877 	/* Verify that the sequence counter is incremented by 1 */
1878 	if (unlikely(resp_msg_hdr->msg_seqno != (req_msg_hdr->msg_seqno + 1)))
1879 		return -EBADMSG;
1880 
1881 	/* Verify response message type and version number. */
1882 	if (resp_msg_hdr->msg_type != (req_msg_hdr->msg_type + 1) ||
1883 	    resp_msg_hdr->msg_version != req_msg_hdr->msg_version)
1884 		return -EBADMSG;
1885 
1886 	/*
1887 	 * If the message size is greater than our buffer length then return
1888 	 * an error.
1889 	 */
1890 	if (unlikely((resp_msg_hdr->msg_sz + ctx->authsize) > req->resp_sz))
1891 		return -EBADMSG;
1892 
1893 	/* Decrypt the payload */
1894 	memcpy(iv, &resp_msg_hdr->msg_seqno, min(sizeof(iv), sizeof(resp_msg_hdr->msg_seqno)));
1895 	if (!aesgcm_decrypt(ctx, req->resp_buf, resp_msg->payload, resp_msg_hdr->msg_sz,
1896 			    &resp_msg_hdr->algo, AAD_LEN, iv, resp_msg_hdr->authtag))
1897 		return -EBADMSG;
1898 
1899 	return 0;
1900 }
1901 
1902 static int enc_payload(struct snp_msg_desc *mdesc, u64 seqno, struct snp_guest_req *req)
1903 {
1904 	struct snp_guest_msg *msg = &mdesc->secret_request;
1905 	struct snp_guest_msg_hdr *hdr = &msg->hdr;
1906 	struct aesgcm_ctx *ctx = mdesc->ctx;
1907 	u8 iv[GCM_AES_IV_SIZE] = {};
1908 
1909 	memset(msg, 0, sizeof(*msg));
1910 
1911 	hdr->algo = SNP_AEAD_AES_256_GCM;
1912 	hdr->hdr_version = MSG_HDR_VER;
1913 	hdr->hdr_sz = sizeof(*hdr);
1914 	hdr->msg_type = req->msg_type;
1915 	hdr->msg_version = req->msg_version;
1916 	hdr->msg_seqno = seqno;
1917 	hdr->msg_vmpck = req->vmpck_id;
1918 	hdr->msg_sz = req->req_sz;
1919 
1920 	/* Verify the sequence number is non-zero */
1921 	if (!hdr->msg_seqno)
1922 		return -ENOSR;
1923 
1924 	pr_debug("request [seqno %lld type %d version %d sz %d]\n",
1925 		 hdr->msg_seqno, hdr->msg_type, hdr->msg_version, hdr->msg_sz);
1926 
1927 	if (WARN_ON((req->req_sz + ctx->authsize) > sizeof(msg->payload)))
1928 		return -EBADMSG;
1929 
1930 	memcpy(iv, &hdr->msg_seqno, min(sizeof(iv), sizeof(hdr->msg_seqno)));
1931 	aesgcm_encrypt(ctx, msg->payload, req->req_buf, req->req_sz, &hdr->algo,
1932 		       AAD_LEN, iv, hdr->authtag);
1933 
1934 	return 0;
1935 }
1936 
1937 static int __handle_guest_request(struct snp_msg_desc *mdesc, struct snp_guest_req *req)
1938 {
1939 	unsigned long req_start = jiffies;
1940 	unsigned int override_npages = 0;
1941 	u64 override_err = 0;
1942 	int rc;
1943 
1944 retry_request:
1945 	/*
1946 	 * Call firmware to process the request. In this function the encrypted
1947 	 * message enters shared memory with the host. So after this call the
1948 	 * sequence number must be incremented or the VMPCK must be deleted to
1949 	 * prevent reuse of the IV.
1950 	 */
1951 	rc = snp_issue_guest_request(req);
1952 	switch (rc) {
1953 	case -ENOSPC:
1954 		/*
1955 		 * If the extended guest request fails due to having too
1956 		 * small of a certificate data buffer, retry the same
1957 		 * guest request without the extended data request in
1958 		 * order to increment the sequence number and thus avoid
1959 		 * IV reuse.
1960 		 */
1961 		override_npages = req->input.data_npages;
1962 		req->exit_code	= SVM_VMGEXIT_GUEST_REQUEST;
1963 
1964 		/*
1965 		 * Override the error to inform callers the given extended
1966 		 * request buffer size was too small and give the caller the
1967 		 * required buffer size.
1968 		 */
1969 		override_err = SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN);
1970 
1971 		/*
1972 		 * If this call to the firmware succeeds, the sequence number can
1973 		 * be incremented allowing for continued use of the VMPCK. If
1974 		 * there is an error reflected in the return value, this value
1975 		 * is checked further down and the result will be the deletion
1976 		 * of the VMPCK and the error code being propagated back to the
1977 		 * user as an ioctl() return code.
1978 		 */
1979 		goto retry_request;
1980 
1981 	/*
1982 	 * The host may return SNP_GUEST_VMM_ERR_BUSY if the request has been
1983 	 * throttled. Retry in the driver to avoid returning and reusing the
1984 	 * message sequence number on a different message.
1985 	 */
1986 	case -EAGAIN:
1987 		if (jiffies - req_start > SNP_REQ_MAX_RETRY_DURATION) {
1988 			rc = -ETIMEDOUT;
1989 			break;
1990 		}
1991 		schedule_timeout_killable(SNP_REQ_RETRY_DELAY);
1992 		goto retry_request;
1993 	}
1994 
1995 	/*
1996 	 * Increment the message sequence number. There is no harm in doing
1997 	 * this now because decryption uses the value stored in the response
1998 	 * structure and any failure will wipe the VMPCK, preventing further
1999 	 * use anyway.
2000 	 */
2001 	snp_inc_msg_seqno(mdesc);
2002 
2003 	if (override_err) {
2004 		req->exitinfo2 = override_err;
2005 
2006 		/*
2007 		 * If an extended guest request was issued and the supplied certificate
2008 		 * buffer was not large enough, a standard guest request was issued to
2009 		 * prevent IV reuse. If the standard request was successful, return -EIO
2010 		 * back to the caller as would have originally been returned.
2011 		 */
2012 		if (!rc && override_err == SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN))
2013 			rc = -EIO;
2014 	}
2015 
2016 	if (override_npages)
2017 		req->input.data_npages = override_npages;
2018 
2019 	return rc;
2020 }
2021 
2022 int snp_send_guest_request(struct snp_msg_desc *mdesc, struct snp_guest_req *req)
2023 {
2024 	u64 seqno;
2025 	int rc;
2026 
2027 	/*
2028 	 * enc_payload() calls aesgcm_encrypt(), which can potentially offload to HW.
2029 	 * The offload's DMA SG list of data to encrypt has to be in linear mapping.
2030 	 */
2031 	if (!virt_addr_valid(req->req_buf) || !virt_addr_valid(req->resp_buf)) {
2032 		pr_warn("AES-GSM buffers must be in linear mapping");
2033 		return -EINVAL;
2034 	}
2035 
2036 	guard(mutex)(&snp_cmd_mutex);
2037 
2038 	/* Check if the VMPCK is not empty */
2039 	if (!mdesc->vmpck || !memchr_inv(mdesc->vmpck, 0, VMPCK_KEY_LEN)) {
2040 		pr_err_ratelimited("VMPCK is disabled\n");
2041 		return -ENOTTY;
2042 	}
2043 
2044 	/* Get message sequence and verify that its a non-zero */
2045 	seqno = snp_get_msg_seqno(mdesc);
2046 	if (!seqno)
2047 		return -EIO;
2048 
2049 	/* Clear shared memory's response for the host to populate. */
2050 	memset(mdesc->response, 0, sizeof(struct snp_guest_msg));
2051 
2052 	/* Encrypt the userspace provided payload in mdesc->secret_request. */
2053 	rc = enc_payload(mdesc, seqno, req);
2054 	if (rc)
2055 		return rc;
2056 
2057 	/*
2058 	 * Write the fully encrypted request to the shared unencrypted
2059 	 * request page.
2060 	 */
2061 	memcpy(mdesc->request, &mdesc->secret_request, sizeof(mdesc->secret_request));
2062 
2063 	/* Initialize the input address for guest request */
2064 	req->input.req_gpa = __pa(mdesc->request);
2065 	req->input.resp_gpa = __pa(mdesc->response);
2066 	req->input.data_gpa = req->certs_data ? __pa(req->certs_data) : 0;
2067 
2068 	rc = __handle_guest_request(mdesc, req);
2069 	if (rc) {
2070 		if (rc == -EIO &&
2071 		    req->exitinfo2 == SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN))
2072 			return rc;
2073 
2074 		pr_alert("Detected error from ASP request. rc: %d, exitinfo2: 0x%llx\n",
2075 			 rc, req->exitinfo2);
2076 
2077 		snp_disable_vmpck(mdesc);
2078 		return rc;
2079 	}
2080 
2081 	rc = verify_and_dec_payload(mdesc, req);
2082 	if (rc) {
2083 		pr_alert("Detected unexpected decode failure from ASP. rc: %d\n", rc);
2084 		snp_disable_vmpck(mdesc);
2085 		return rc;
2086 	}
2087 
2088 	return 0;
2089 }
2090 EXPORT_SYMBOL_GPL(snp_send_guest_request);
2091 
2092 static int __init snp_get_tsc_info(void)
2093 {
2094 	struct snp_tsc_info_resp *tsc_resp;
2095 	struct snp_tsc_info_req *tsc_req;
2096 	struct snp_msg_desc *mdesc;
2097 	struct snp_guest_req req = {};
2098 	int rc = -ENOMEM;
2099 
2100 	tsc_req = kzalloc(sizeof(*tsc_req), GFP_KERNEL);
2101 	if (!tsc_req)
2102 		return rc;
2103 
2104 	/*
2105 	 * The intermediate response buffer is used while decrypting the
2106 	 * response payload. Make sure that it has enough space to cover
2107 	 * the authtag.
2108 	 */
2109 	tsc_resp = kzalloc(sizeof(*tsc_resp) + AUTHTAG_LEN, GFP_KERNEL);
2110 	if (!tsc_resp)
2111 		goto e_free_tsc_req;
2112 
2113 	mdesc = snp_msg_alloc();
2114 	if (IS_ERR_OR_NULL(mdesc))
2115 		goto e_free_tsc_resp;
2116 
2117 	rc = snp_msg_init(mdesc, snp_vmpl);
2118 	if (rc)
2119 		goto e_free_mdesc;
2120 
2121 	req.msg_version = MSG_HDR_VER;
2122 	req.msg_type = SNP_MSG_TSC_INFO_REQ;
2123 	req.vmpck_id = snp_vmpl;
2124 	req.req_buf = tsc_req;
2125 	req.req_sz = sizeof(*tsc_req);
2126 	req.resp_buf = (void *)tsc_resp;
2127 	req.resp_sz = sizeof(*tsc_resp) + AUTHTAG_LEN;
2128 	req.exit_code = SVM_VMGEXIT_GUEST_REQUEST;
2129 
2130 	rc = snp_send_guest_request(mdesc, &req);
2131 	if (rc)
2132 		goto e_request;
2133 
2134 	pr_debug("%s: response status 0x%x scale 0x%llx offset 0x%llx factor 0x%x\n",
2135 		 __func__, tsc_resp->status, tsc_resp->tsc_scale, tsc_resp->tsc_offset,
2136 		 tsc_resp->tsc_factor);
2137 
2138 	if (!tsc_resp->status) {
2139 		snp_tsc_scale = tsc_resp->tsc_scale;
2140 		snp_tsc_offset = tsc_resp->tsc_offset;
2141 	} else {
2142 		pr_err("Failed to get TSC info, response status 0x%x\n", tsc_resp->status);
2143 		rc = -EIO;
2144 	}
2145 
2146 e_request:
2147 	/* The response buffer contains sensitive data, explicitly clear it. */
2148 	memzero_explicit(tsc_resp, sizeof(*tsc_resp) + AUTHTAG_LEN);
2149 e_free_mdesc:
2150 	snp_msg_free(mdesc);
2151 e_free_tsc_resp:
2152 	kfree(tsc_resp);
2153 e_free_tsc_req:
2154 	kfree(tsc_req);
2155 
2156 	return rc;
2157 }
2158 
2159 void __init snp_secure_tsc_prepare(void)
2160 {
2161 	if (!cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC))
2162 		return;
2163 
2164 	if (snp_get_tsc_info()) {
2165 		pr_alert("Unable to retrieve Secure TSC info from ASP\n");
2166 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SECURE_TSC);
2167 	}
2168 
2169 	pr_debug("SecureTSC enabled");
2170 }
2171 
2172 static unsigned long securetsc_get_tsc_khz(void)
2173 {
2174 	return snp_tsc_freq_khz;
2175 }
2176 
2177 void __init snp_secure_tsc_init(void)
2178 {
2179 	struct snp_secrets_page *secrets;
2180 	unsigned long tsc_freq_mhz;
2181 	void *mem;
2182 
2183 	if (!cc_platform_has(CC_ATTR_GUEST_SNP_SECURE_TSC))
2184 		return;
2185 
2186 	mem = early_memremap_encrypted(sev_secrets_pa, PAGE_SIZE);
2187 	if (!mem) {
2188 		pr_err("Unable to get TSC_FACTOR: failed to map the SNP secrets page.\n");
2189 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SECURE_TSC);
2190 	}
2191 
2192 	secrets = (__force struct snp_secrets_page *)mem;
2193 
2194 	setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ);
2195 	rdmsrq(MSR_AMD64_GUEST_TSC_FREQ, tsc_freq_mhz);
2196 
2197 	/* Extract the GUEST TSC MHZ from BIT[17:0], rest is reserved space */
2198 	tsc_freq_mhz &= GENMASK_ULL(17, 0);
2199 
2200 	snp_tsc_freq_khz = SNP_SCALE_TSC_FREQ(tsc_freq_mhz * 1000, secrets->tsc_factor);
2201 
2202 	x86_platform.calibrate_cpu = securetsc_get_tsc_khz;
2203 	x86_platform.calibrate_tsc = securetsc_get_tsc_khz;
2204 
2205 	early_memunmap(mem, PAGE_SIZE);
2206 }
2207