xref: /linux/arch/x86/boot/startup/sev-shared.c (revision 9723dd0c705eb626bac2cd06b83a2c8514ed697a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * AMD Encrypted Register State Support
4  *
5  * Author: Joerg Roedel <jroedel@suse.de>
6  *
7  * This file is not compiled stand-alone. It contains code shared
8  * between the pre-decompression boot code and the running Linux kernel
9  * and is included directly into both code-bases.
10  */
11 
12 #include <asm/setup_data.h>
13 
14 #ifndef __BOOT_COMPRESSED
15 #define error(v)			pr_err(v)
16 #define has_cpuflag(f)			boot_cpu_has(f)
17 #else
18 #undef WARN
19 #define WARN(condition, format...) (!!(condition))
20 #endif
21 
22 /* Copy of the SNP firmware's CPUID page. */
23 static struct snp_cpuid_table cpuid_table_copy __ro_after_init;
24 
25 /*
26  * These will be initialized based on CPUID table so that non-present
27  * all-zero leaves (for sparse tables) can be differentiated from
28  * invalid/out-of-range leaves. This is needed since all-zero leaves
29  * still need to be post-processed.
30  */
31 static u32 cpuid_std_range_max __ro_after_init;
32 static u32 cpuid_hyp_range_max __ro_after_init;
33 static u32 cpuid_ext_range_max __ro_after_init;
34 
35 bool sev_snp_needs_sfw;
36 
37 void __head __noreturn
38 sev_es_terminate(unsigned int set, unsigned int reason)
39 {
40 	u64 val = GHCB_MSR_TERM_REQ;
41 
42 	/* Tell the hypervisor what went wrong. */
43 	val |= GHCB_SEV_TERM_REASON(set, reason);
44 
45 	/* Request Guest Termination from Hypervisor */
46 	sev_es_wr_ghcb_msr(val);
47 	VMGEXIT();
48 
49 	while (true)
50 		asm volatile("hlt\n" : : : "memory");
51 }
52 
53 /*
54  * The hypervisor features are available from GHCB version 2 onward.
55  */
56 u64 get_hv_features(void)
57 {
58 	u64 val;
59 
60 	if (ghcb_version < 2)
61 		return 0;
62 
63 	sev_es_wr_ghcb_msr(GHCB_MSR_HV_FT_REQ);
64 	VMGEXIT();
65 
66 	val = sev_es_rd_ghcb_msr();
67 	if (GHCB_RESP_CODE(val) != GHCB_MSR_HV_FT_RESP)
68 		return 0;
69 
70 	return GHCB_MSR_HV_FT_RESP_VAL(val);
71 }
72 
73 int svsm_process_result_codes(struct svsm_call *call)
74 {
75 	switch (call->rax_out) {
76 	case SVSM_SUCCESS:
77 		return 0;
78 	case SVSM_ERR_INCOMPLETE:
79 	case SVSM_ERR_BUSY:
80 		return -EAGAIN;
81 	default:
82 		return -EINVAL;
83 	}
84 }
85 
86 /*
87  * Issue a VMGEXIT to call the SVSM:
88  *   - Load the SVSM register state (RAX, RCX, RDX, R8 and R9)
89  *   - Set the CA call pending field to 1
90  *   - Issue VMGEXIT
91  *   - Save the SVSM return register state (RAX, RCX, RDX, R8 and R9)
92  *   - Perform atomic exchange of the CA call pending field
93  *
94  *   - See the "Secure VM Service Module for SEV-SNP Guests" specification for
95  *     details on the calling convention.
96  *     - The calling convention loosely follows the Microsoft X64 calling
97  *       convention by putting arguments in RCX, RDX, R8 and R9.
98  *     - RAX specifies the SVSM protocol/callid as input and the return code
99  *       as output.
100  */
101 void svsm_issue_call(struct svsm_call *call, u8 *pending)
102 {
103 	register unsigned long rax asm("rax") = call->rax;
104 	register unsigned long rcx asm("rcx") = call->rcx;
105 	register unsigned long rdx asm("rdx") = call->rdx;
106 	register unsigned long r8  asm("r8")  = call->r8;
107 	register unsigned long r9  asm("r9")  = call->r9;
108 
109 	call->caa->call_pending = 1;
110 
111 	asm volatile("rep; vmmcall\n\t"
112 		     : "+r" (rax), "+r" (rcx), "+r" (rdx), "+r" (r8), "+r" (r9)
113 		     : : "memory");
114 
115 	*pending = xchg(&call->caa->call_pending, *pending);
116 
117 	call->rax_out = rax;
118 	call->rcx_out = rcx;
119 	call->rdx_out = rdx;
120 	call->r8_out  = r8;
121 	call->r9_out  = r9;
122 }
123 
124 int svsm_perform_msr_protocol(struct svsm_call *call)
125 {
126 	u8 pending = 0;
127 	u64 val, resp;
128 
129 	/*
130 	 * When using the MSR protocol, be sure to save and restore
131 	 * the current MSR value.
132 	 */
133 	val = sev_es_rd_ghcb_msr();
134 
135 	sev_es_wr_ghcb_msr(GHCB_MSR_VMPL_REQ_LEVEL(0));
136 
137 	svsm_issue_call(call, &pending);
138 
139 	resp = sev_es_rd_ghcb_msr();
140 
141 	sev_es_wr_ghcb_msr(val);
142 
143 	if (pending)
144 		return -EINVAL;
145 
146 	if (GHCB_RESP_CODE(resp) != GHCB_MSR_VMPL_RESP)
147 		return -EINVAL;
148 
149 	if (GHCB_MSR_VMPL_RESP_VAL(resp))
150 		return -EINVAL;
151 
152 	return svsm_process_result_codes(call);
153 }
154 
155 static int __sev_cpuid_hv(u32 fn, int reg_idx, u32 *reg)
156 {
157 	u64 val;
158 
159 	sev_es_wr_ghcb_msr(GHCB_CPUID_REQ(fn, reg_idx));
160 	VMGEXIT();
161 	val = sev_es_rd_ghcb_msr();
162 	if (GHCB_RESP_CODE(val) != GHCB_MSR_CPUID_RESP)
163 		return -EIO;
164 
165 	*reg = (val >> 32);
166 
167 	return 0;
168 }
169 
170 static int __sev_cpuid_hv_msr(struct cpuid_leaf *leaf)
171 {
172 	int ret;
173 
174 	/*
175 	 * MSR protocol does not support fetching non-zero subfunctions, but is
176 	 * sufficient to handle current early-boot cases. Should that change,
177 	 * make sure to report an error rather than ignoring the index and
178 	 * grabbing random values. If this issue arises in the future, handling
179 	 * can be added here to use GHCB-page protocol for cases that occur late
180 	 * enough in boot that GHCB page is available.
181 	 */
182 	if (cpuid_function_is_indexed(leaf->fn) && leaf->subfn)
183 		return -EINVAL;
184 
185 	ret =         __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EAX, &leaf->eax);
186 	ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EBX, &leaf->ebx);
187 	ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_ECX, &leaf->ecx);
188 	ret = ret ? : __sev_cpuid_hv(leaf->fn, GHCB_CPUID_REQ_EDX, &leaf->edx);
189 
190 	return ret;
191 }
192 
193 
194 
195 /*
196  * This may be called early while still running on the initial identity
197  * mapping. Use RIP-relative addressing to obtain the correct address
198  * while running with the initial identity mapping as well as the
199  * switch-over to kernel virtual addresses later.
200  */
201 const struct snp_cpuid_table *snp_cpuid_get_table(void)
202 {
203 	return rip_rel_ptr(&cpuid_table_copy);
204 }
205 
206 /*
207  * The SNP Firmware ABI, Revision 0.9, Section 7.1, details the use of
208  * XCR0_IN and XSS_IN to encode multiple versions of 0xD subfunctions 0
209  * and 1 based on the corresponding features enabled by a particular
210  * combination of XCR0 and XSS registers so that a guest can look up the
211  * version corresponding to the features currently enabled in its XCR0/XSS
212  * registers. The only values that differ between these versions/table
213  * entries is the enabled XSAVE area size advertised via EBX.
214  *
215  * While hypervisors may choose to make use of this support, it is more
216  * robust/secure for a guest to simply find the entry corresponding to the
217  * base/legacy XSAVE area size (XCR0=1 or XCR0=3), and then calculate the
218  * XSAVE area size using subfunctions 2 through 64, as documented in APM
219  * Volume 3, Rev 3.31, Appendix E.3.8, which is what is done here.
220  *
221  * Since base/legacy XSAVE area size is documented as 0x240, use that value
222  * directly rather than relying on the base size in the CPUID table.
223  *
224  * Return: XSAVE area size on success, 0 otherwise.
225  */
226 static u32 __head snp_cpuid_calc_xsave_size(u64 xfeatures_en, bool compacted)
227 {
228 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
229 	u64 xfeatures_found = 0;
230 	u32 xsave_size = 0x240;
231 	int i;
232 
233 	for (i = 0; i < cpuid_table->count; i++) {
234 		const struct snp_cpuid_fn *e = &cpuid_table->fn[i];
235 
236 		if (!(e->eax_in == 0xD && e->ecx_in > 1 && e->ecx_in < 64))
237 			continue;
238 		if (!(xfeatures_en & (BIT_ULL(e->ecx_in))))
239 			continue;
240 		if (xfeatures_found & (BIT_ULL(e->ecx_in)))
241 			continue;
242 
243 		xfeatures_found |= (BIT_ULL(e->ecx_in));
244 
245 		if (compacted)
246 			xsave_size += e->eax;
247 		else
248 			xsave_size = max(xsave_size, e->eax + e->ebx);
249 	}
250 
251 	/*
252 	 * Either the guest set unsupported XCR0/XSS bits, or the corresponding
253 	 * entries in the CPUID table were not present. This is not a valid
254 	 * state to be in.
255 	 */
256 	if (xfeatures_found != (xfeatures_en & GENMASK_ULL(63, 2)))
257 		return 0;
258 
259 	return xsave_size;
260 }
261 
262 static bool __head
263 snp_cpuid_get_validated_func(struct cpuid_leaf *leaf)
264 {
265 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
266 	int i;
267 
268 	for (i = 0; i < cpuid_table->count; i++) {
269 		const struct snp_cpuid_fn *e = &cpuid_table->fn[i];
270 
271 		if (e->eax_in != leaf->fn)
272 			continue;
273 
274 		if (cpuid_function_is_indexed(leaf->fn) && e->ecx_in != leaf->subfn)
275 			continue;
276 
277 		/*
278 		 * For 0xD subfunctions 0 and 1, only use the entry corresponding
279 		 * to the base/legacy XSAVE area size (XCR0=1 or XCR0=3, XSS=0).
280 		 * See the comments above snp_cpuid_calc_xsave_size() for more
281 		 * details.
282 		 */
283 		if (e->eax_in == 0xD && (e->ecx_in == 0 || e->ecx_in == 1))
284 			if (!(e->xcr0_in == 1 || e->xcr0_in == 3) || e->xss_in)
285 				continue;
286 
287 		leaf->eax = e->eax;
288 		leaf->ebx = e->ebx;
289 		leaf->ecx = e->ecx;
290 		leaf->edx = e->edx;
291 
292 		return true;
293 	}
294 
295 	return false;
296 }
297 
298 static void snp_cpuid_hv_msr(void *ctx, struct cpuid_leaf *leaf)
299 {
300 	if (__sev_cpuid_hv_msr(leaf))
301 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID_HV);
302 }
303 
304 static int __head
305 snp_cpuid_postprocess(void (*cpuid_fn)(void *ctx, struct cpuid_leaf *leaf),
306 		      void *ctx, struct cpuid_leaf *leaf)
307 {
308 	struct cpuid_leaf leaf_hv = *leaf;
309 
310 	switch (leaf->fn) {
311 	case 0x1:
312 		cpuid_fn(ctx, &leaf_hv);
313 
314 		/* initial APIC ID */
315 		leaf->ebx = (leaf_hv.ebx & GENMASK(31, 24)) | (leaf->ebx & GENMASK(23, 0));
316 		/* APIC enabled bit */
317 		leaf->edx = (leaf_hv.edx & BIT(9)) | (leaf->edx & ~BIT(9));
318 
319 		/* OSXSAVE enabled bit */
320 		if (native_read_cr4() & X86_CR4_OSXSAVE)
321 			leaf->ecx |= BIT(27);
322 		break;
323 	case 0x7:
324 		/* OSPKE enabled bit */
325 		leaf->ecx &= ~BIT(4);
326 		if (native_read_cr4() & X86_CR4_PKE)
327 			leaf->ecx |= BIT(4);
328 		break;
329 	case 0xB:
330 		leaf_hv.subfn = 0;
331 		cpuid_fn(ctx, &leaf_hv);
332 
333 		/* extended APIC ID */
334 		leaf->edx = leaf_hv.edx;
335 		break;
336 	case 0xD: {
337 		bool compacted = false;
338 		u64 xcr0 = 1, xss = 0;
339 		u32 xsave_size;
340 
341 		if (leaf->subfn != 0 && leaf->subfn != 1)
342 			return 0;
343 
344 		if (native_read_cr4() & X86_CR4_OSXSAVE)
345 			xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
346 		if (leaf->subfn == 1) {
347 			/* Get XSS value if XSAVES is enabled. */
348 			if (leaf->eax & BIT(3)) {
349 				unsigned long lo, hi;
350 
351 				asm volatile("rdmsr" : "=a" (lo), "=d" (hi)
352 						     : "c" (MSR_IA32_XSS));
353 				xss = (hi << 32) | lo;
354 			}
355 
356 			/*
357 			 * The PPR and APM aren't clear on what size should be
358 			 * encoded in 0xD:0x1:EBX when compaction is not enabled
359 			 * by either XSAVEC (feature bit 1) or XSAVES (feature
360 			 * bit 3) since SNP-capable hardware has these feature
361 			 * bits fixed as 1. KVM sets it to 0 in this case, but
362 			 * to avoid this becoming an issue it's safer to simply
363 			 * treat this as unsupported for SNP guests.
364 			 */
365 			if (!(leaf->eax & (BIT(1) | BIT(3))))
366 				return -EINVAL;
367 
368 			compacted = true;
369 		}
370 
371 		xsave_size = snp_cpuid_calc_xsave_size(xcr0 | xss, compacted);
372 		if (!xsave_size)
373 			return -EINVAL;
374 
375 		leaf->ebx = xsave_size;
376 		}
377 		break;
378 	case 0x8000001E:
379 		cpuid_fn(ctx, &leaf_hv);
380 
381 		/* extended APIC ID */
382 		leaf->eax = leaf_hv.eax;
383 		/* compute ID */
384 		leaf->ebx = (leaf->ebx & GENMASK(31, 8)) | (leaf_hv.ebx & GENMASK(7, 0));
385 		/* node ID */
386 		leaf->ecx = (leaf->ecx & GENMASK(31, 8)) | (leaf_hv.ecx & GENMASK(7, 0));
387 		break;
388 	default:
389 		/* No fix-ups needed, use values as-is. */
390 		break;
391 	}
392 
393 	return 0;
394 }
395 
396 /*
397  * Returns -EOPNOTSUPP if feature not enabled. Any other non-zero return value
398  * should be treated as fatal by caller.
399  */
400 int __head snp_cpuid(void (*cpuid_fn)(void *ctx, struct cpuid_leaf *leaf),
401 		     void *ctx, struct cpuid_leaf *leaf)
402 {
403 	const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
404 
405 	if (!cpuid_table->count)
406 		return -EOPNOTSUPP;
407 
408 	if (!snp_cpuid_get_validated_func(leaf)) {
409 		/*
410 		 * Some hypervisors will avoid keeping track of CPUID entries
411 		 * where all values are zero, since they can be handled the
412 		 * same as out-of-range values (all-zero). This is useful here
413 		 * as well as it allows virtually all guest configurations to
414 		 * work using a single SNP CPUID table.
415 		 *
416 		 * To allow for this, there is a need to distinguish between
417 		 * out-of-range entries and in-range zero entries, since the
418 		 * CPUID table entries are only a template that may need to be
419 		 * augmented with additional values for things like
420 		 * CPU-specific information during post-processing. So if it's
421 		 * not in the table, set the values to zero. Then, if they are
422 		 * within a valid CPUID range, proceed with post-processing
423 		 * using zeros as the initial values. Otherwise, skip
424 		 * post-processing and just return zeros immediately.
425 		 */
426 		leaf->eax = leaf->ebx = leaf->ecx = leaf->edx = 0;
427 
428 		/* Skip post-processing for out-of-range zero leafs. */
429 		if (!(leaf->fn <= cpuid_std_range_max ||
430 		      (leaf->fn >= 0x40000000 && leaf->fn <= cpuid_hyp_range_max) ||
431 		      (leaf->fn >= 0x80000000 && leaf->fn <= cpuid_ext_range_max)))
432 			return 0;
433 	}
434 
435 	return snp_cpuid_postprocess(cpuid_fn, ctx, leaf);
436 }
437 
438 /*
439  * Boot VC Handler - This is the first VC handler during boot, there is no GHCB
440  * page yet, so it only supports the MSR based communication with the
441  * hypervisor and only the CPUID exit-code.
442  */
443 void __head do_vc_no_ghcb(struct pt_regs *regs, unsigned long exit_code)
444 {
445 	unsigned int subfn = lower_bits(regs->cx, 32);
446 	unsigned int fn = lower_bits(regs->ax, 32);
447 	u16 opcode = *(unsigned short *)regs->ip;
448 	struct cpuid_leaf leaf;
449 	int ret;
450 
451 	/* Only CPUID is supported via MSR protocol */
452 	if (exit_code != SVM_EXIT_CPUID)
453 		goto fail;
454 
455 	/* Is it really a CPUID insn? */
456 	if (opcode != 0xa20f)
457 		goto fail;
458 
459 	leaf.fn = fn;
460 	leaf.subfn = subfn;
461 
462 	ret = snp_cpuid(snp_cpuid_hv_msr, NULL, &leaf);
463 	if (!ret)
464 		goto cpuid_done;
465 
466 	if (ret != -EOPNOTSUPP)
467 		goto fail;
468 
469 	if (__sev_cpuid_hv_msr(&leaf))
470 		goto fail;
471 
472 cpuid_done:
473 	regs->ax = leaf.eax;
474 	regs->bx = leaf.ebx;
475 	regs->cx = leaf.ecx;
476 	regs->dx = leaf.edx;
477 
478 	/*
479 	 * This is a VC handler and the #VC is only raised when SEV-ES is
480 	 * active, which means SEV must be active too. Do sanity checks on the
481 	 * CPUID results to make sure the hypervisor does not trick the kernel
482 	 * into the no-sev path. This could map sensitive data unencrypted and
483 	 * make it accessible to the hypervisor.
484 	 *
485 	 * In particular, check for:
486 	 *	- Availability of CPUID leaf 0x8000001f
487 	 *	- SEV CPUID bit.
488 	 *
489 	 * The hypervisor might still report the wrong C-bit position, but this
490 	 * can't be checked here.
491 	 */
492 
493 	if (fn == 0x80000000 && (regs->ax < 0x8000001f))
494 		/* SEV leaf check */
495 		goto fail;
496 	else if ((fn == 0x8000001f && !(regs->ax & BIT(1))))
497 		/* SEV bit */
498 		goto fail;
499 
500 	/* Skip over the CPUID two-byte opcode */
501 	regs->ip += 2;
502 
503 	return;
504 
505 fail:
506 	/* Terminate the guest */
507 	sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
508 }
509 
510 struct cc_setup_data {
511 	struct setup_data header;
512 	u32 cc_blob_address;
513 };
514 
515 /*
516  * Search for a Confidential Computing blob passed in as a setup_data entry
517  * via the Linux Boot Protocol.
518  */
519 static __head
520 struct cc_blob_sev_info *find_cc_blob_setup_data(struct boot_params *bp)
521 {
522 	struct cc_setup_data *sd = NULL;
523 	struct setup_data *hdr;
524 
525 	hdr = (struct setup_data *)bp->hdr.setup_data;
526 
527 	while (hdr) {
528 		if (hdr->type == SETUP_CC_BLOB) {
529 			sd = (struct cc_setup_data *)hdr;
530 			return (struct cc_blob_sev_info *)(unsigned long)sd->cc_blob_address;
531 		}
532 		hdr = (struct setup_data *)hdr->next;
533 	}
534 
535 	return NULL;
536 }
537 
538 /*
539  * Initialize the kernel's copy of the SNP CPUID table, and set up the
540  * pointer that will be used to access it.
541  *
542  * Maintaining a direct mapping of the SNP CPUID table used by firmware would
543  * be possible as an alternative, but the approach is brittle since the
544  * mapping needs to be updated in sync with all the changes to virtual memory
545  * layout and related mapping facilities throughout the boot process.
546  */
547 static void __head setup_cpuid_table(const struct cc_blob_sev_info *cc_info)
548 {
549 	const struct snp_cpuid_table *cpuid_table_fw, *cpuid_table;
550 	int i;
551 
552 	if (!cc_info || !cc_info->cpuid_phys || cc_info->cpuid_len < PAGE_SIZE)
553 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID);
554 
555 	cpuid_table_fw = (const struct snp_cpuid_table *)cc_info->cpuid_phys;
556 	if (!cpuid_table_fw->count || cpuid_table_fw->count > SNP_CPUID_COUNT_MAX)
557 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_CPUID);
558 
559 	cpuid_table = snp_cpuid_get_table();
560 	memcpy((void *)cpuid_table, cpuid_table_fw, sizeof(*cpuid_table));
561 
562 	/* Initialize CPUID ranges for range-checking. */
563 	for (i = 0; i < cpuid_table->count; i++) {
564 		const struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
565 
566 		if (fn->eax_in == 0x0)
567 			cpuid_std_range_max = fn->eax;
568 		else if (fn->eax_in == 0x40000000)
569 			cpuid_hyp_range_max = fn->eax;
570 		else if (fn->eax_in == 0x80000000)
571 			cpuid_ext_range_max = fn->eax;
572 	}
573 }
574 
575 static int __head svsm_call_msr_protocol(struct svsm_call *call)
576 {
577 	int ret;
578 
579 	do {
580 		ret = svsm_perform_msr_protocol(call);
581 	} while (ret == -EAGAIN);
582 
583 	return ret;
584 }
585 
586 static void __head svsm_pval_4k_page(unsigned long paddr, bool validate,
587 				     struct svsm_ca *caa, u64 caa_pa)
588 {
589 	struct svsm_pvalidate_call *pc;
590 	struct svsm_call call = {};
591 	unsigned long flags;
592 	u64 pc_pa;
593 
594 	/*
595 	 * This can be called very early in the boot, use native functions in
596 	 * order to avoid paravirt issues.
597 	 */
598 	flags = native_local_irq_save();
599 
600 	call.caa = caa;
601 
602 	pc = (struct svsm_pvalidate_call *)call.caa->svsm_buffer;
603 	pc_pa = caa_pa + offsetof(struct svsm_ca, svsm_buffer);
604 
605 	pc->num_entries = 1;
606 	pc->cur_index   = 0;
607 	pc->entry[0].page_size = RMP_PG_SIZE_4K;
608 	pc->entry[0].action    = validate;
609 	pc->entry[0].ignore_cf = 0;
610 	pc->entry[0].rsvd      = 0;
611 	pc->entry[0].pfn       = paddr >> PAGE_SHIFT;
612 
613 	/* Protocol 0, Call ID 1 */
614 	call.rax = SVSM_CORE_CALL(SVSM_CORE_PVALIDATE);
615 	call.rcx = pc_pa;
616 
617 	/*
618 	 * Use the MSR protocol exclusively, so that this code is usable in
619 	 * startup code where VA/PA translations of the GHCB page's address may
620 	 * be problematic.
621 	 */
622 	if (svsm_call_msr_protocol(&call))
623 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
624 
625 	native_local_irq_restore(flags);
626 }
627 
628 static void __head pvalidate_4k_page(unsigned long vaddr, unsigned long paddr,
629 				     bool validate, struct svsm_ca *caa, u64 caa_pa)
630 {
631 	int ret;
632 
633 	if (snp_vmpl) {
634 		svsm_pval_4k_page(paddr, validate, caa, caa_pa);
635 	} else {
636 		ret = pvalidate(vaddr, RMP_PG_SIZE_4K, validate);
637 		if (ret)
638 			sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PVALIDATE);
639 	}
640 
641 	/*
642 	 * If validating memory (making it private) and affected by the
643 	 * cache-coherency vulnerability, perform the cache eviction mitigation.
644 	 */
645 	if (validate && sev_snp_needs_sfw)
646 		sev_evict_cache((void *)vaddr, 1);
647 }
648 
649 static void __head __page_state_change(unsigned long vaddr, unsigned long paddr,
650 				       const struct psc_desc *desc)
651 {
652 	u64 val, msr;
653 
654 	/*
655 	 * If private -> shared then invalidate the page before requesting the
656 	 * state change in the RMP table.
657 	 */
658 	if (desc->op == SNP_PAGE_STATE_SHARED)
659 		pvalidate_4k_page(vaddr, paddr, false, desc->ca, desc->caa_pa);
660 
661 	/* Save the current GHCB MSR value */
662 	msr = sev_es_rd_ghcb_msr();
663 
664 	/* Issue VMGEXIT to change the page state in RMP table. */
665 	sev_es_wr_ghcb_msr(GHCB_MSR_PSC_REQ_GFN(paddr >> PAGE_SHIFT, desc->op));
666 	VMGEXIT();
667 
668 	/* Read the response of the VMGEXIT. */
669 	val = sev_es_rd_ghcb_msr();
670 	if ((GHCB_RESP_CODE(val) != GHCB_MSR_PSC_RESP) || GHCB_MSR_PSC_RESP_VAL(val))
671 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
672 
673 	/* Restore the GHCB MSR value */
674 	sev_es_wr_ghcb_msr(msr);
675 
676 	/*
677 	 * Now that page state is changed in the RMP table, validate it so that it is
678 	 * consistent with the RMP entry.
679 	 */
680 	if (desc->op == SNP_PAGE_STATE_PRIVATE)
681 		pvalidate_4k_page(vaddr, paddr, true, desc->ca, desc->caa_pa);
682 }
683 
684 /*
685  * Maintain the GPA of the SVSM Calling Area (CA) in order to utilize the SVSM
686  * services needed when not running in VMPL0.
687  */
688 static bool __head svsm_setup_ca(const struct cc_blob_sev_info *cc_info,
689 				 void *page)
690 {
691 	struct snp_secrets_page *secrets_page;
692 	struct snp_cpuid_table *cpuid_table;
693 	unsigned int i;
694 	u64 caa;
695 
696 	BUILD_BUG_ON(sizeof(*secrets_page) != PAGE_SIZE);
697 
698 	/*
699 	 * Check if running at VMPL0.
700 	 *
701 	 * Use RMPADJUST (see the rmpadjust() function for a description of what
702 	 * the instruction does) to update the VMPL1 permissions of a page. If
703 	 * the guest is running at VMPL0, this will succeed and implies there is
704 	 * no SVSM. If the guest is running at any other VMPL, this will fail.
705 	 * Linux SNP guests only ever run at a single VMPL level so permission mask
706 	 * changes of a lesser-privileged VMPL are a don't-care.
707 	 *
708 	 * Use a rip-relative reference to obtain the proper address, since this
709 	 * routine is running identity mapped when called, both by the decompressor
710 	 * code and the early kernel code.
711 	 */
712 	if (!rmpadjust((unsigned long)page, RMP_PG_SIZE_4K, 1))
713 		return false;
714 
715 	/*
716 	 * Not running at VMPL0, ensure everything has been properly supplied
717 	 * for running under an SVSM.
718 	 */
719 	if (!cc_info || !cc_info->secrets_phys || cc_info->secrets_len != PAGE_SIZE)
720 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SECRETS_PAGE);
721 
722 	secrets_page = (struct snp_secrets_page *)cc_info->secrets_phys;
723 	if (!secrets_page->svsm_size)
724 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_NO_SVSM);
725 
726 	if (!secrets_page->svsm_guest_vmpl)
727 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SVSM_VMPL0);
728 
729 	snp_vmpl = secrets_page->svsm_guest_vmpl;
730 
731 	caa = secrets_page->svsm_caa;
732 
733 	/*
734 	 * An open-coded PAGE_ALIGNED() in order to avoid including
735 	 * kernel-proper headers into the decompressor.
736 	 */
737 	if (caa & (PAGE_SIZE - 1))
738 		sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_SVSM_CAA);
739 
740 	boot_svsm_caa_pa = caa;
741 
742 	/* Advertise the SVSM presence via CPUID. */
743 	cpuid_table = (struct snp_cpuid_table *)snp_cpuid_get_table();
744 	for (i = 0; i < cpuid_table->count; i++) {
745 		struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
746 
747 		if (fn->eax_in == 0x8000001f)
748 			fn->eax |= BIT(28);
749 	}
750 
751 	return true;
752 }
753