xref: /linux/arch/x86/kvm/svm/sev.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM-SEV support
6  *
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/kvm_types.h>
12 #include <linux/kvm_host.h>
13 #include <linux/kernel.h>
14 #include <linux/highmem.h>
15 #include <linux/psp.h>
16 #include <linux/psp-sev.h>
17 #include <linux/pagemap.h>
18 #include <linux/swap.h>
19 #include <linux/misc_cgroup.h>
20 #include <linux/processor.h>
21 #include <linux/trace_events.h>
22 #include <uapi/linux/sev-guest.h>
23 
24 #include <asm/pkru.h>
25 #include <asm/trapnr.h>
26 #include <asm/cpuid/api.h>
27 #include <asm/fpu/xcr.h>
28 #include <asm/fpu/xstate.h>
29 #include <asm/debugreg.h>
30 #include <asm/msr.h>
31 #include <asm/sev.h>
32 
33 #include "mmu.h"
34 #include "x86.h"
35 #include "svm.h"
36 #include "svm_ops.h"
37 #include "cpuid.h"
38 #include "trace.h"
39 
40 #define GHCB_VERSION_MAX	2ULL
41 #define GHCB_VERSION_MIN	1ULL
42 
43 #define GHCB_HV_FT_SUPPORTED	(GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)
44 
45 /*
46  * The GHCB spec essentially states that all non-zero error codes other than
47  * those explicitly defined above should be treated as an error by the guest.
48  * Define a generic error to cover that case, and choose a value that is not
49  * likely to overlap with new explicit error codes should more be added to
50  * the GHCB spec later. KVM will use this to report generic errors when
51  * handling SNP guest requests.
52  */
53 #define SNP_GUEST_VMM_ERR_GENERIC       (~0U)
54 
55 /* enable/disable SEV support */
56 static bool __ro_after_init sev_enabled = true;
57 module_param_named(sev, sev_enabled, bool, 0444);
58 
59 /* enable/disable SEV-ES support */
60 static bool __ro_after_init sev_es_enabled = true;
61 module_param_named(sev_es, sev_es_enabled, bool, 0444);
62 
63 /* enable/disable SEV-SNP support */
64 static bool __ro_after_init sev_snp_enabled = true;
65 module_param_named(sev_snp, sev_snp_enabled, bool, 0444);
66 
67 static unsigned int __ro_after_init nr_ciphertext_hiding_asids;
68 module_param_named(ciphertext_hiding_asids, nr_ciphertext_hiding_asids, uint, 0444);
69 
70 #define AP_RESET_HOLD_NONE		0
71 #define AP_RESET_HOLD_NAE_EVENT		1
72 #define AP_RESET_HOLD_MSR_PROTO		2
73 
74 /*
75  * SEV-SNP policy bits that can be supported by KVM. These include policy bits
76  * that have implementation support within KVM or policy bits that do not
77  * require implementation support within KVM to enforce the policy.
78  */
79 #define KVM_SNP_POLICY_MASK_VALID	(SNP_POLICY_MASK_API_MINOR		| \
80 					 SNP_POLICY_MASK_API_MAJOR		| \
81 					 SNP_POLICY_MASK_SMT			| \
82 					 SNP_POLICY_MASK_RSVD_MBO		| \
83 					 SNP_POLICY_MASK_DEBUG			| \
84 					 SNP_POLICY_MASK_SINGLE_SOCKET		| \
85 					 SNP_POLICY_MASK_CXL_ALLOW		| \
86 					 SNP_POLICY_MASK_MEM_AES_256_XTS	| \
87 					 SNP_POLICY_MASK_RAPL_DIS		| \
88 					 SNP_POLICY_MASK_CIPHERTEXT_HIDING_DRAM	| \
89 					 SNP_POLICY_MASK_PAGE_SWAP_DISABLE)
90 
91 static u64 snp_supported_policy_bits __ro_after_init;
92 
93 static u64 sev_supported_vmsa_features __ro_after_init;
94 
95 #define INITIAL_VMSA_GPA 0xFFFFFFFFF000
96 
97 static u8 sev_enc_bit;
98 static DECLARE_RWSEM(sev_deactivate_lock);
99 static DEFINE_MUTEX(sev_bitmap_lock);
100 /* Protects kvm_sev_info's enc_context_owner, mirror_vms and mirror_entry.  */
101 static DEFINE_MUTEX(sev_mirror_lock);
102 unsigned int max_sev_asid;
103 static unsigned int min_sev_asid;
104 static unsigned int max_sev_es_asid;
105 static unsigned int min_sev_es_asid;
106 static unsigned int max_snp_asid;
107 static unsigned int min_snp_asid;
108 static unsigned long sev_me_mask;
109 static unsigned int nr_asids;
110 static unsigned long *sev_asid_bitmap;
111 static unsigned long *sev_reclaim_asid_bitmap;
112 
113 static __always_inline void kvm_lockdep_assert_sev_lock_held(struct kvm *kvm)
114 {
115 #ifdef CONFIG_PROVE_LOCKING
116 	/*
117 	 * Querying SEV+ support is safe if there are no other references, i.e.
118 	 * if concurrent initialization of SEV+ is impossible.
119 	 */
120 	if (!refcount_read(&kvm->users_count))
121 		return;
122 
123 	/*
124 	 * Querying SEV+ support from vCPU context is always safe, as vCPUs can
125 	 * only be created after SEV+ is initialized (and KVM disallows all SEV
126 	 * sub-ioctls while vCPU creation is in-progress).
127 	 */
128 	if (kvm_get_running_vcpu())
129 		return;
130 
131 	lockdep_assert_held(&kvm->lock);
132 #endif
133 }
134 
135 static bool sev_guest(struct kvm *kvm)
136 {
137 	kvm_lockdep_assert_sev_lock_held(kvm);
138 	return ____sev_guest(kvm);
139 }
140 static bool sev_es_guest(struct kvm *kvm)
141 {
142 	kvm_lockdep_assert_sev_lock_held(kvm);
143 	return ____sev_es_guest(kvm);
144 }
145 
146 static bool sev_snp_guest(struct kvm *kvm)
147 {
148 	kvm_lockdep_assert_sev_lock_held(kvm);
149 	return ____sev_snp_guest(kvm);
150 }
151 
152 static int snp_decommission_context(struct kvm *kvm);
153 
154 struct enc_region {
155 	struct list_head list;
156 	unsigned long npages;
157 	struct page **pages;
158 	unsigned long uaddr;
159 	unsigned long size;
160 };
161 
162 /* Called with the sev_bitmap_lock held, or on shutdown  */
163 static int sev_flush_asids(unsigned int min_asid, unsigned int max_asid)
164 {
165 	int ret, error = 0;
166 	unsigned int asid;
167 
168 	/* Check if there are any ASIDs to reclaim before performing a flush */
169 	asid = find_next_bit(sev_reclaim_asid_bitmap, nr_asids, min_asid);
170 	if (asid > max_asid)
171 		return -EBUSY;
172 
173 	/*
174 	 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
175 	 * so it must be guarded.
176 	 */
177 	down_write(&sev_deactivate_lock);
178 
179 	/* SNP firmware requires use of WBINVD for ASID recycling. */
180 	wbinvd_on_all_cpus();
181 
182 	if (sev_snp_enabled)
183 		ret = sev_do_cmd(SEV_CMD_SNP_DF_FLUSH, NULL, &error);
184 	else
185 		ret = sev_guest_df_flush(&error);
186 
187 	up_write(&sev_deactivate_lock);
188 
189 	if (ret)
190 		pr_err("SEV%s: DF_FLUSH failed, ret=%d, error=%#x\n",
191 		       sev_snp_enabled ? "-SNP" : "", ret, error);
192 
193 	return ret;
194 }
195 
196 static inline bool is_mirroring_enc_context(struct kvm *kvm)
197 {
198 	return !!to_kvm_sev_info(kvm)->enc_context_owner;
199 }
200 
201 static bool sev_vcpu_has_debug_swap(struct vcpu_svm *svm)
202 {
203 	struct kvm_vcpu *vcpu = &svm->vcpu;
204 	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
205 
206 	return sev->vmsa_features & SVM_SEV_FEAT_DEBUG_SWAP;
207 }
208 
209 static bool snp_is_secure_tsc_enabled(struct kvm *kvm)
210 {
211 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
212 
213 	return (sev->vmsa_features & SVM_SEV_FEAT_SECURE_TSC) &&
214 	       !WARN_ON_ONCE(!sev_snp_guest(kvm));
215 }
216 
217 /* Must be called with the sev_bitmap_lock held */
218 static bool __sev_recycle_asids(unsigned int min_asid, unsigned int max_asid)
219 {
220 	if (sev_flush_asids(min_asid, max_asid))
221 		return false;
222 
223 	/* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */
224 	bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
225 		   nr_asids);
226 	bitmap_zero(sev_reclaim_asid_bitmap, nr_asids);
227 
228 	return true;
229 }
230 
231 static int sev_misc_cg_try_charge(struct kvm_sev_info *sev)
232 {
233 	enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
234 	return misc_cg_try_charge(type, sev->misc_cg, 1);
235 }
236 
237 static void sev_misc_cg_uncharge(struct kvm_sev_info *sev)
238 {
239 	enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
240 	misc_cg_uncharge(type, sev->misc_cg, 1);
241 }
242 
243 static unsigned int sev_alloc_asid(unsigned int min_asid, unsigned int max_asid)
244 {
245 	unsigned int asid;
246 	bool retry = true;
247 
248 	guard(mutex)(&sev_bitmap_lock);
249 
250 again:
251 	asid = find_next_zero_bit(sev_asid_bitmap, max_asid + 1, min_asid);
252 	if (asid > max_asid) {
253 		if (retry && __sev_recycle_asids(min_asid, max_asid)) {
254 			retry = false;
255 			goto again;
256 		}
257 
258 		return asid;
259 	}
260 
261 	__set_bit(asid, sev_asid_bitmap);
262 	return asid;
263 }
264 
265 static int sev_asid_new(struct kvm_sev_info *sev, unsigned long vm_type)
266 {
267 	/*
268 	 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid.
269 	 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1.
270 	 */
271 	unsigned int min_asid, max_asid, asid;
272 	int ret;
273 
274 	if (vm_type == KVM_X86_SNP_VM) {
275 		min_asid = min_snp_asid;
276 		max_asid = max_snp_asid;
277 	} else if (sev->es_active) {
278 		min_asid = min_sev_es_asid;
279 		max_asid = max_sev_es_asid;
280 	} else {
281 		min_asid = min_sev_asid;
282 		max_asid = max_sev_asid;
283 	}
284 
285 	/*
286 	 * The min ASID can end up larger than the max if basic SEV support is
287 	 * effectively disabled by disallowing use of ASIDs for SEV guests.
288 	 * Similarly for SEV-ES guests the min ASID can end up larger than the
289 	 * max when ciphertext hiding is enabled, effectively disabling SEV-ES
290 	 * support.
291 	 */
292 	if (min_asid > max_asid)
293 		return -ENOTTY;
294 
295 	WARN_ON_ONCE(sev->misc_cg);
296 	sev->misc_cg = get_current_misc_cg();
297 	ret = sev_misc_cg_try_charge(sev);
298 	if (ret)
299 		goto e_put_cg;
300 
301 	asid = sev_alloc_asid(min_asid, max_asid);
302 	if (asid > max_asid) {
303 		ret = -EBUSY;
304 		goto e_uncharge;
305 	}
306 
307 	sev->asid = asid;
308 	return 0;
309 
310 e_uncharge:
311 	sev_misc_cg_uncharge(sev);
312 e_put_cg:
313 	put_misc_cg(sev->misc_cg);
314 	sev->misc_cg = NULL;
315 	return ret;
316 }
317 
318 static unsigned int sev_get_asid(struct kvm *kvm)
319 {
320 	return to_kvm_sev_info(kvm)->asid;
321 }
322 
323 static void sev_asid_free(struct kvm_sev_info *sev)
324 {
325 	struct svm_cpu_data *sd;
326 	int cpu;
327 
328 	mutex_lock(&sev_bitmap_lock);
329 
330 	__set_bit(sev->asid, sev_reclaim_asid_bitmap);
331 
332 	for_each_possible_cpu(cpu) {
333 		sd = per_cpu_ptr(&svm_data, cpu);
334 		sd->sev_vmcbs[sev->asid] = NULL;
335 	}
336 
337 	mutex_unlock(&sev_bitmap_lock);
338 
339 	sev_misc_cg_uncharge(sev);
340 	put_misc_cg(sev->misc_cg);
341 	sev->misc_cg = NULL;
342 }
343 
344 static void sev_decommission(unsigned int handle)
345 {
346 	struct sev_data_decommission decommission;
347 
348 	if (!handle)
349 		return;
350 
351 	decommission.handle = handle;
352 	sev_guest_decommission(&decommission, NULL);
353 }
354 
355 /*
356  * Transition a page to hypervisor-owned/shared state in the RMP table. This
357  * should not fail under normal conditions, but leak the page should that
358  * happen since it will no longer be usable by the host due to RMP protections.
359  */
360 static int kvm_rmp_make_shared(struct kvm *kvm, u64 pfn, enum pg_level level)
361 {
362 	if (KVM_BUG_ON(rmp_make_shared(pfn, level), kvm)) {
363 		snp_leak_pages(pfn, page_level_size(level) >> PAGE_SHIFT);
364 		return -EIO;
365 	}
366 
367 	return 0;
368 }
369 
370 /*
371  * Certain page-states, such as Pre-Guest and Firmware pages (as documented
372  * in Chapter 5 of the SEV-SNP Firmware ABI under "Page States") cannot be
373  * directly transitioned back to normal/hypervisor-owned state via RMPUPDATE
374  * unless they are reclaimed first.
375  *
376  * Until they are reclaimed and subsequently transitioned via RMPUPDATE, they
377  * might not be usable by the host due to being set as immutable or still
378  * being associated with a guest ASID.
379  *
380  * Bug the VM and leak the page if reclaim fails, or if the RMP entry can't be
381  * converted back to shared, as the page is no longer usable due to RMP
382  * protections, and it's infeasible for the guest to continue on.
383  */
384 static int snp_page_reclaim(struct kvm *kvm, u64 pfn)
385 {
386 	struct sev_data_snp_page_reclaim data = {0};
387 	int fw_err, rc;
388 
389 	data.paddr = __sme_set(pfn << PAGE_SHIFT);
390 	rc = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &fw_err);
391 	if (KVM_BUG(rc, kvm, "Failed to reclaim PFN %llx, rc %d fw_err %d", pfn, rc, fw_err)) {
392 		snp_leak_pages(pfn, 1);
393 		return -EIO;
394 	}
395 
396 	if (kvm_rmp_make_shared(kvm, pfn, PG_LEVEL_4K))
397 		return -EIO;
398 
399 	return rc;
400 }
401 
402 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
403 {
404 	struct sev_data_deactivate deactivate;
405 
406 	if (!handle)
407 		return;
408 
409 	deactivate.handle = handle;
410 
411 	/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
412 	down_read(&sev_deactivate_lock);
413 	sev_guest_deactivate(&deactivate, NULL);
414 	up_read(&sev_deactivate_lock);
415 
416 	sev_decommission(handle);
417 }
418 
419 /*
420  * This sets up bounce buffers/firmware pages to handle SNP Guest Request
421  * messages (e.g. attestation requests). See "SNP Guest Request" in the GHCB
422  * 2.0 specification for more details.
423  *
424  * Technically, when an SNP Guest Request is issued, the guest will provide its
425  * own request/response pages, which could in theory be passed along directly
426  * to firmware rather than using bounce pages. However, these pages would need
427  * special care:
428  *
429  *   - Both pages are from shared guest memory, so they need to be protected
430  *     from migration/etc. occurring while firmware reads/writes to them. At a
431  *     minimum, this requires elevating the ref counts and potentially needing
432  *     an explicit pinning of the memory. This places additional restrictions
433  *     on what type of memory backends userspace can use for shared guest
434  *     memory since there is some reliance on using refcounted pages.
435  *
436  *   - The response page needs to be switched to Firmware-owned[1] state
437  *     before the firmware can write to it, which can lead to potential
438  *     host RMP #PFs if the guest is misbehaved and hands the host a
439  *     guest page that KVM might write to for other reasons (e.g. virtio
440  *     buffers/etc.).
441  *
442  * Both of these issues can be avoided completely by using separately-allocated
443  * bounce pages for both the request/response pages and passing those to
444  * firmware instead. So that's what is being set up here.
445  *
446  * Guest requests rely on message sequence numbers to ensure requests are
447  * issued to firmware in the order the guest issues them, so concurrent guest
448  * requests generally shouldn't happen. But a misbehaved guest could issue
449  * concurrent guest requests in theory, so a mutex is used to serialize
450  * access to the bounce buffers.
451  *
452  * [1] See the "Page States" section of the SEV-SNP Firmware ABI for more
453  *     details on Firmware-owned pages, along with "RMP and VMPL Access Checks"
454  *     in the APM for details on the related RMP restrictions.
455  */
456 static int snp_guest_req_init(struct kvm *kvm)
457 {
458 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
459 	struct page *req_page;
460 
461 	req_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
462 	if (!req_page)
463 		return -ENOMEM;
464 
465 	sev->guest_resp_buf = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
466 	if (!sev->guest_resp_buf) {
467 		__free_page(req_page);
468 		return -EIO;
469 	}
470 
471 	sev->guest_req_buf = page_address(req_page);
472 	mutex_init(&sev->guest_req_mutex);
473 
474 	return 0;
475 }
476 
477 static void snp_guest_req_cleanup(struct kvm *kvm)
478 {
479 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
480 
481 	if (sev->guest_resp_buf)
482 		snp_free_firmware_page(sev->guest_resp_buf);
483 
484 	if (sev->guest_req_buf)
485 		__free_page(virt_to_page(sev->guest_req_buf));
486 
487 	sev->guest_req_buf = NULL;
488 	sev->guest_resp_buf = NULL;
489 }
490 
491 static int __sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp,
492 			    struct kvm_sev_init *data,
493 			    unsigned long vm_type)
494 {
495 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
496 	struct sev_platform_init_args init_args = {0};
497 	bool es_active = vm_type != KVM_X86_SEV_VM;
498 	bool snp_active = vm_type == KVM_X86_SNP_VM;
499 	u64 valid_vmsa_features = es_active ? sev_supported_vmsa_features : 0;
500 	int ret;
501 
502 	if (kvm->created_vcpus)
503 		return -EINVAL;
504 
505 	if (data->flags)
506 		return -EINVAL;
507 
508 	if (!snp_active)
509 		valid_vmsa_features &= ~SVM_SEV_FEAT_SECURE_TSC;
510 
511 	if (data->vmsa_features & ~valid_vmsa_features)
512 		return -EINVAL;
513 
514 	if (data->ghcb_version > GHCB_VERSION_MAX || (!es_active && data->ghcb_version))
515 		return -EINVAL;
516 
517 	/*
518 	 * KVM supports the full range of mandatory features defined by version
519 	 * 2 of the GHCB protocol, so default to that for SEV-ES guests created
520 	 * via KVM_SEV_INIT2 (KVM_SEV_INIT forces version 1).
521 	 */
522 	if (es_active && !data->ghcb_version)
523 		data->ghcb_version = 2;
524 
525 	if (snp_active && data->ghcb_version < 2)
526 		return -EINVAL;
527 
528 	if (unlikely(sev->active))
529 		return -EINVAL;
530 
531 	sev->active = true;
532 	sev->es_active = es_active;
533 	sev->vmsa_features = data->vmsa_features;
534 	sev->ghcb_version = data->ghcb_version;
535 
536 	if (snp_active)
537 		sev->vmsa_features |= SVM_SEV_FEAT_SNP_ACTIVE;
538 
539 	ret = sev_asid_new(sev, vm_type);
540 	if (ret)
541 		goto e_no_asid;
542 
543 	init_args.probe = false;
544 	ret = sev_platform_init(&init_args);
545 	if (ret)
546 		goto e_free_asid;
547 
548 	if (!zalloc_cpumask_var(&sev->have_run_cpus, GFP_KERNEL_ACCOUNT)) {
549 		ret = -ENOMEM;
550 		goto e_free_asid;
551 	}
552 
553 	/* This needs to happen after SEV/SNP firmware initialization. */
554 	if (snp_active) {
555 		ret = snp_guest_req_init(kvm);
556 		if (ret)
557 			goto e_free;
558 	}
559 
560 	INIT_LIST_HEAD(&sev->regions_list);
561 	INIT_LIST_HEAD(&sev->mirror_vms);
562 	sev->need_init = false;
563 
564 	kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_SEV);
565 
566 	return 0;
567 
568 e_free:
569 	free_cpumask_var(sev->have_run_cpus);
570 e_free_asid:
571 	argp->error = init_args.error;
572 	sev_asid_free(sev);
573 	sev->asid = 0;
574 e_no_asid:
575 	sev->vmsa_features = 0;
576 	sev->es_active = false;
577 	sev->active = false;
578 	return ret;
579 }
580 
581 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
582 {
583 	struct kvm_sev_init data = {
584 		.vmsa_features = 0,
585 		.ghcb_version = 0,
586 	};
587 	unsigned long vm_type;
588 
589 	if (kvm->arch.vm_type != KVM_X86_DEFAULT_VM)
590 		return -EINVAL;
591 
592 	vm_type = (argp->id == KVM_SEV_INIT ? KVM_X86_SEV_VM : KVM_X86_SEV_ES_VM);
593 
594 	/*
595 	 * KVM_SEV_ES_INIT has been deprecated by KVM_SEV_INIT2, so it will
596 	 * continue to only ever support the minimal GHCB protocol version.
597 	 */
598 	if (vm_type == KVM_X86_SEV_ES_VM)
599 		data.ghcb_version = GHCB_VERSION_MIN;
600 
601 	return __sev_guest_init(kvm, argp, &data, vm_type);
602 }
603 
604 static int sev_guest_init2(struct kvm *kvm, struct kvm_sev_cmd *argp)
605 {
606 	struct kvm_sev_init data;
607 
608 	if (!to_kvm_sev_info(kvm)->need_init)
609 		return -EINVAL;
610 
611 	if (kvm->arch.vm_type != KVM_X86_SEV_VM &&
612 	    kvm->arch.vm_type != KVM_X86_SEV_ES_VM &&
613 	    kvm->arch.vm_type != KVM_X86_SNP_VM)
614 		return -EINVAL;
615 
616 	if (copy_from_user(&data, u64_to_user_ptr(argp->data), sizeof(data)))
617 		return -EFAULT;
618 
619 	return __sev_guest_init(kvm, argp, &data, kvm->arch.vm_type);
620 }
621 
622 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
623 {
624 	unsigned int asid = sev_get_asid(kvm);
625 	struct sev_data_activate activate;
626 	int ret;
627 
628 	/* activate ASID on the given handle */
629 	activate.handle = handle;
630 	activate.asid   = asid;
631 	ret = sev_guest_activate(&activate, error);
632 
633 	return ret;
634 }
635 
636 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
637 {
638 	CLASS(fd, f)(fd);
639 
640 	if (fd_empty(f))
641 		return -EBADF;
642 
643 	return sev_issue_cmd_external_user(fd_file(f), id, data, error);
644 }
645 
646 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
647 {
648 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
649 
650 	return __sev_issue_cmd(sev->fd, id, data, error);
651 }
652 
653 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
654 {
655 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
656 	struct sev_data_launch_start start;
657 	struct kvm_sev_launch_start params;
658 	void *dh_blob, *session_blob;
659 	int *error = &argp->error;
660 	int ret;
661 
662 	if (!sev_guest(kvm))
663 		return -ENOTTY;
664 
665 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
666 		return -EFAULT;
667 
668 	memset(&start, 0, sizeof(start));
669 
670 	dh_blob = NULL;
671 	if (params.dh_uaddr) {
672 		dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
673 		if (IS_ERR(dh_blob))
674 			return PTR_ERR(dh_blob);
675 
676 		start.dh_cert_address = __sme_set(__pa(dh_blob));
677 		start.dh_cert_len = params.dh_len;
678 	}
679 
680 	session_blob = NULL;
681 	if (params.session_uaddr) {
682 		session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
683 		if (IS_ERR(session_blob)) {
684 			ret = PTR_ERR(session_blob);
685 			goto e_free_dh;
686 		}
687 
688 		start.session_address = __sme_set(__pa(session_blob));
689 		start.session_len = params.session_len;
690 	}
691 
692 	start.handle = params.handle;
693 	start.policy = params.policy;
694 
695 	/* create memory encryption context */
696 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, &start, error);
697 	if (ret)
698 		goto e_free_session;
699 
700 	/* Bind ASID to this guest */
701 	ret = sev_bind_asid(kvm, start.handle, error);
702 	if (ret) {
703 		sev_decommission(start.handle);
704 		goto e_free_session;
705 	}
706 
707 	/* return handle to userspace */
708 	params.handle = start.handle;
709 	if (copy_to_user(u64_to_user_ptr(argp->data), &params, sizeof(params))) {
710 		sev_unbind_asid(kvm, start.handle);
711 		ret = -EFAULT;
712 		goto e_free_session;
713 	}
714 
715 	sev->policy = params.policy;
716 	sev->handle = start.handle;
717 	sev->fd = argp->sev_fd;
718 
719 e_free_session:
720 	kfree(session_blob);
721 e_free_dh:
722 	kfree(dh_blob);
723 	return ret;
724 }
725 
726 static int sev_check_pin_count(struct kvm *kvm, unsigned long npages)
727 {
728 	unsigned long total_npages, lock_limit;
729 
730 	total_npages = to_kvm_sev_info(kvm)->pages_locked + npages;
731 	if (total_npages > totalram_pages())
732 		return -EINVAL;
733 
734 	lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
735 	if (total_npages > lock_limit && !capable(CAP_IPC_LOCK)) {
736 		pr_err_ratelimited("SEV: %lu total pages would exceed the lock limit of %lu.\n",
737 				   total_npages, lock_limit);
738 		return -ENOMEM;
739 	}
740 
741 	return 0;
742 }
743 
744 static int sev_pin_user_pages(struct kvm *kvm, unsigned long addr, int npages,
745 			      unsigned int gup_flags, struct page **pages)
746 {
747 	int npinned;
748 
749 	lockdep_assert_held(&kvm->lock);
750 
751 	npinned = pin_user_pages_fast(addr, npages, gup_flags, pages);
752 	if (npinned != npages) {
753 		if (npinned > 0)
754 			unpin_user_pages(pages, npinned);
755 		pr_err_ratelimited("SEV: Failure locking %u pages.\n", npages);
756 		return -ENOMEM;
757 	}
758 
759 	to_kvm_sev_info(kvm)->pages_locked += npages;
760 	return 0;
761 }
762 
763 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
764 				    unsigned long ulen, unsigned long *n,
765 				    unsigned int flags)
766 {
767 	unsigned long npages;
768 	struct page **pages;
769 	int ret;
770 
771 	lockdep_assert_held(&kvm->lock);
772 
773 	if (ulen == 0 || uaddr + ulen < uaddr)
774 		return ERR_PTR(-EINVAL);
775 
776 	/*
777 	 * Calculate the number of pages that need to be pinned to cover the
778 	 * entire range.  Note!  This isn't simply PFN_DOWN(ulen), as KVM
779 	 * doesn't require the incoming address+size to be page aligned!
780 	 */
781 	npages = PFN_DOWN(uaddr + ulen - 1) - PFN_DOWN(uaddr) + 1;
782 	if (npages > INT_MAX)
783 		return ERR_PTR(-EINVAL);
784 
785 	ret = sev_check_pin_count(kvm, npages);
786 	if (ret)
787 		return ERR_PTR(ret);
788 
789 	/*
790 	 * Don't WARN if the kernel (rightly) thinks the total size is absurd,
791 	 * i.e. rely on the kernel to reject outrageous range sizes.  The above
792 	 * check on the number of pages is purely to avoid truncation as
793 	 * pin_user_pages_fast() takes the number of pages as a 32-bit int.
794 	 */
795 	pages = kvzalloc_objs(*pages, npages, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
796 	if (!pages)
797 		return ERR_PTR(-ENOMEM);
798 
799 	ret = sev_pin_user_pages(kvm, uaddr, npages, flags, pages);
800 	if (ret) {
801 		kvfree(pages);
802 		return ERR_PTR(ret);
803 	}
804 
805 	*n = npages;
806 	return pages;
807 }
808 
809 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
810 			     unsigned long npages)
811 {
812 	unpin_user_pages(pages, npages);
813 	kvfree(pages);
814 	to_kvm_sev_info(kvm)->pages_locked -= npages;
815 }
816 
817 static struct page *sev_pin_page(struct kvm *kvm, unsigned long addr,
818 				 unsigned int flags)
819 {
820 	struct page *page;
821 	int r;
822 
823 	r = sev_check_pin_count(kvm, 1);
824 	if (r)
825 		return ERR_PTR(r);
826 
827 	r = sev_pin_user_pages(kvm, addr, 1, flags, &page);
828 	if (r)
829 		return ERR_PTR(r);
830 
831 	return page;
832 }
833 
834 static void sev_unpin_page(struct kvm *kvm, struct page *page)
835 {
836 	unpin_user_pages(&page, 1);
837 	to_kvm_sev_info(kvm)->pages_locked -= 1;
838 }
839 
840 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
841 {
842 	uint8_t *page_virtual;
843 	unsigned long i;
844 
845 	if (this_cpu_has(X86_FEATURE_SME_COHERENT) || npages == 0 ||
846 	    pages == NULL)
847 		return;
848 
849 	for (i = 0; i < npages; i++) {
850 		page_virtual = kmap_local_page(pages[i]);
851 		clflush_cache_range(page_virtual, PAGE_SIZE);
852 		kunmap_local(page_virtual);
853 		cond_resched();
854 	}
855 }
856 
857 static void sev_writeback_caches(struct kvm *kvm)
858 {
859 	/*
860 	 * Ensure that all dirty guest tagged cache entries are written back
861 	 * before releasing the pages back to the system for use.  CLFLUSH will
862 	 * not do this without SME_COHERENT, and flushing many cache lines
863 	 * individually is slower than blasting WBINVD for large VMs, so issue
864 	 * WBNOINVD (or WBINVD if the "no invalidate" variant is unsupported)
865 	 * on CPUs that have done VMRUN, i.e. may have dirtied data using the
866 	 * VM's ASID.
867 	 *
868 	 * For simplicity, never remove CPUs from the bitmap.  Ideally, KVM
869 	 * would clear the mask when flushing caches, but doing so requires
870 	 * serializing multiple calls and having responding CPUs (to the IPI)
871 	 * mark themselves as still running if they are running (or about to
872 	 * run) a vCPU for the VM.
873 	 *
874 	 * Note, the caller is responsible for ensuring correctness if the mask
875 	 * can be modified, e.g. if a CPU could be doing VMRUN.
876 	 */
877 	wbnoinvd_on_cpus_mask(to_kvm_sev_info(kvm)->have_run_cpus);
878 }
879 
880 static unsigned long get_num_contig_pages(unsigned long idx,
881 				struct page **inpages, unsigned long npages)
882 {
883 	unsigned long paddr, next_paddr;
884 	unsigned long i = idx + 1, pages = 1;
885 
886 	/* find the number of contiguous pages starting from idx */
887 	paddr = __sme_page_pa(inpages[idx]);
888 	while (i < npages) {
889 		next_paddr = __sme_page_pa(inpages[i++]);
890 		if ((paddr + PAGE_SIZE) == next_paddr) {
891 			pages++;
892 			paddr = next_paddr;
893 			continue;
894 		}
895 		break;
896 	}
897 
898 	return pages;
899 }
900 
901 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
902 {
903 	unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
904 	struct kvm_sev_launch_update_data params;
905 	struct sev_data_launch_update_data data;
906 	struct page **inpages;
907 	int ret;
908 
909 	if (!sev_guest(kvm))
910 		return -ENOTTY;
911 
912 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
913 		return -EFAULT;
914 
915 	vaddr = params.uaddr;
916 	size = params.len;
917 	vaddr_end = vaddr + size;
918 
919 	/* Lock the user memory. */
920 	inpages = sev_pin_memory(kvm, vaddr, size, &npages, FOLL_WRITE);
921 	if (IS_ERR(inpages))
922 		return PTR_ERR(inpages);
923 
924 	/*
925 	 * Flush (on non-coherent CPUs) before LAUNCH_UPDATE encrypts pages in
926 	 * place; the cache may contain the data that was written unencrypted.
927 	 */
928 	sev_clflush_pages(inpages, npages);
929 
930 	data.reserved = 0;
931 	data.handle = to_kvm_sev_info(kvm)->handle;
932 
933 	for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
934 		int offset, len;
935 
936 		/*
937 		 * If the user buffer is not page-aligned, calculate the offset
938 		 * within the page.
939 		 */
940 		offset = vaddr & (PAGE_SIZE - 1);
941 
942 		/* Calculate the number of pages that can be encrypted in one go. */
943 		pages = get_num_contig_pages(i, inpages, npages);
944 
945 		len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
946 
947 		data.len = len;
948 		data.address = __sme_page_pa(inpages[i]) + offset;
949 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, &data, &argp->error);
950 		if (ret)
951 			goto e_unpin;
952 
953 		size -= len;
954 		next_vaddr = vaddr + len;
955 	}
956 
957 e_unpin:
958 	/* content of memory is updated, mark pages dirty */
959 	for (i = 0; i < npages; i++) {
960 		set_page_dirty_lock(inpages[i]);
961 		mark_page_accessed(inpages[i]);
962 	}
963 	/* unlock the user pages */
964 	sev_unpin_memory(kvm, inpages, npages);
965 	return ret;
966 }
967 
968 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
969 {
970 	struct kvm_vcpu *vcpu = &svm->vcpu;
971 	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
972 	struct sev_es_save_area *save = svm->sev_es.vmsa;
973 	struct xregs_state *xsave;
974 	const u8 *s;
975 	u8 *d;
976 	int i;
977 
978 	lockdep_assert_held(&vcpu->mutex);
979 
980 	if (vcpu->arch.guest_state_protected)
981 		return -EINVAL;
982 
983 	/* Check some debug related fields before encrypting the VMSA */
984 	if (svm->vcpu.guest_debug || (svm->vmcb->save.dr7 & ~DR7_FIXED_1))
985 		return -EINVAL;
986 
987 	/*
988 	 * SEV-ES will use a VMSA that is pointed to by the VMCB, not
989 	 * the traditional VMSA that is part of the VMCB. Copy the
990 	 * traditional VMSA as it has been built so far (in prep
991 	 * for LAUNCH_UPDATE_VMSA) to be the initial SEV-ES state.
992 	 */
993 	memcpy(save, &svm->vmcb->save, sizeof(svm->vmcb->save));
994 
995 	/* Sync registgers */
996 	save->rax = svm->vcpu.arch.regs[VCPU_REGS_RAX];
997 	save->rbx = svm->vcpu.arch.regs[VCPU_REGS_RBX];
998 	save->rcx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
999 	save->rdx = svm->vcpu.arch.regs[VCPU_REGS_RDX];
1000 	save->rsp = svm->vcpu.arch.regs[VCPU_REGS_RSP];
1001 	save->rbp = svm->vcpu.arch.regs[VCPU_REGS_RBP];
1002 	save->rsi = svm->vcpu.arch.regs[VCPU_REGS_RSI];
1003 	save->rdi = svm->vcpu.arch.regs[VCPU_REGS_RDI];
1004 #ifdef CONFIG_X86_64
1005 	save->r8  = svm->vcpu.arch.regs[VCPU_REGS_R8];
1006 	save->r9  = svm->vcpu.arch.regs[VCPU_REGS_R9];
1007 	save->r10 = svm->vcpu.arch.regs[VCPU_REGS_R10];
1008 	save->r11 = svm->vcpu.arch.regs[VCPU_REGS_R11];
1009 	save->r12 = svm->vcpu.arch.regs[VCPU_REGS_R12];
1010 	save->r13 = svm->vcpu.arch.regs[VCPU_REGS_R13];
1011 	save->r14 = svm->vcpu.arch.regs[VCPU_REGS_R14];
1012 	save->r15 = svm->vcpu.arch.regs[VCPU_REGS_R15];
1013 #endif
1014 	save->rip = svm->vcpu.arch.rip;
1015 
1016 	/* Sync some non-GPR registers before encrypting */
1017 	save->xcr0 = svm->vcpu.arch.xcr0;
1018 	save->pkru = svm->vcpu.arch.pkru;
1019 	save->xss  = svm->vcpu.arch.ia32_xss;
1020 	save->dr6  = svm->vcpu.arch.dr6;
1021 
1022 	save->sev_features = sev->vmsa_features;
1023 
1024 	/*
1025 	 * Skip FPU and AVX setup with KVM_SEV_ES_INIT to avoid
1026 	 * breaking older measurements.
1027 	 */
1028 	if (vcpu->kvm->arch.vm_type != KVM_X86_DEFAULT_VM) {
1029 		xsave = &vcpu->arch.guest_fpu.fpstate->regs.xsave;
1030 		save->x87_dp = xsave->i387.rdp;
1031 		save->mxcsr = xsave->i387.mxcsr;
1032 		save->x87_ftw = xsave->i387.twd;
1033 		save->x87_fsw = xsave->i387.swd;
1034 		save->x87_fcw = xsave->i387.cwd;
1035 		save->x87_fop = xsave->i387.fop;
1036 		save->x87_ds = 0;
1037 		save->x87_cs = 0;
1038 		save->x87_rip = xsave->i387.rip;
1039 
1040 		for (i = 0; i < 8; i++) {
1041 			/*
1042 			 * The format of the x87 save area is undocumented and
1043 			 * definitely not what you would expect.  It consists of
1044 			 * an 8*8 bytes area with bytes 0-7, and an 8*2 bytes
1045 			 * area with bytes 8-9 of each register.
1046 			 */
1047 			d = save->fpreg_x87 + i * 8;
1048 			s = ((u8 *)xsave->i387.st_space) + i * 16;
1049 			memcpy(d, s, 8);
1050 			save->fpreg_x87[64 + i * 2] = s[8];
1051 			save->fpreg_x87[64 + i * 2 + 1] = s[9];
1052 		}
1053 		memcpy(save->fpreg_xmm, xsave->i387.xmm_space, 256);
1054 
1055 		s = get_xsave_addr(xsave, XFEATURE_YMM);
1056 		if (s)
1057 			memcpy(save->fpreg_ymm, s, 256);
1058 		else
1059 			memset(save->fpreg_ymm, 0, 256);
1060 	}
1061 
1062 	pr_debug("Virtual Machine Save Area (VMSA):\n");
1063 	print_hex_dump_debug("", DUMP_PREFIX_NONE, 16, 1, save, sizeof(*save), false);
1064 
1065 	return 0;
1066 }
1067 
1068 static int __sev_launch_update_vmsa(struct kvm *kvm, struct kvm_vcpu *vcpu,
1069 				    int *error)
1070 {
1071 	struct sev_data_launch_update_vmsa vmsa;
1072 	struct vcpu_svm *svm = to_svm(vcpu);
1073 	int ret;
1074 
1075 	if (vcpu->guest_debug) {
1076 		pr_warn_once("KVM_SET_GUEST_DEBUG for SEV-ES guest is not supported");
1077 		return -EINVAL;
1078 	}
1079 
1080 	/* Perform some pre-encryption checks against the VMSA */
1081 	ret = sev_es_sync_vmsa(svm);
1082 	if (ret)
1083 		return ret;
1084 
1085 	/*
1086 	 * The LAUNCH_UPDATE_VMSA command will perform in-place encryption of
1087 	 * the VMSA memory content (i.e it will write the same memory region
1088 	 * with the guest's key), so invalidate it first.
1089 	 */
1090 	clflush_cache_range(svm->sev_es.vmsa, PAGE_SIZE);
1091 
1092 	vmsa.reserved = 0;
1093 	vmsa.handle = to_kvm_sev_info(kvm)->handle;
1094 	vmsa.address = __sme_pa(svm->sev_es.vmsa);
1095 	vmsa.len = PAGE_SIZE;
1096 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_VMSA, &vmsa, error);
1097 	if (ret)
1098 	  return ret;
1099 
1100 	/*
1101 	 * SEV-ES guests maintain an encrypted version of their FPU
1102 	 * state which is restored and saved on VMRUN and VMEXIT.
1103 	 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't
1104 	 * do xsave/xrstor on it.
1105 	 */
1106 	fpstate_set_confidential(&vcpu->arch.guest_fpu);
1107 	vcpu->arch.guest_state_protected = true;
1108 
1109 	/*
1110 	 * SEV-ES guest mandates LBR Virtualization to be _always_ ON. Enable it
1111 	 * only after setting guest_state_protected because KVM_SET_MSRS allows
1112 	 * dynamic toggling of LBRV (for performance reason) on write access to
1113 	 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set.
1114 	 */
1115 	svm_enable_lbrv(vcpu);
1116 	return 0;
1117 }
1118 
1119 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
1120 {
1121 	struct kvm_vcpu *vcpu;
1122 	unsigned long i;
1123 	int ret;
1124 
1125 	if (!sev_es_guest(kvm))
1126 		return -ENOTTY;
1127 
1128 	if (kvm_is_vcpu_creation_in_progress(kvm))
1129 		return -EBUSY;
1130 
1131 	ret = kvm_lock_all_vcpus(kvm);
1132 	if (ret)
1133 		return ret;
1134 
1135 	kvm_for_each_vcpu(i, vcpu, kvm) {
1136 		ret = __sev_launch_update_vmsa(kvm, vcpu, &argp->error);
1137 		if (ret)
1138 			break;
1139 	}
1140 
1141 	kvm_unlock_all_vcpus(kvm);
1142 	return ret;
1143 }
1144 
1145 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
1146 {
1147 	void __user *measure = u64_to_user_ptr(argp->data);
1148 	struct sev_data_launch_measure data;
1149 	struct kvm_sev_launch_measure params;
1150 	void __user *p = NULL;
1151 	void *blob = NULL;
1152 	int ret;
1153 
1154 	if (!sev_guest(kvm))
1155 		return -ENOTTY;
1156 
1157 	if (copy_from_user(&params, measure, sizeof(params)))
1158 		return -EFAULT;
1159 
1160 	memset(&data, 0, sizeof(data));
1161 
1162 	/* User wants to query the blob length */
1163 	if (!params.len)
1164 		goto cmd;
1165 
1166 	p = u64_to_user_ptr(params.uaddr);
1167 	if (p) {
1168 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
1169 			return -EINVAL;
1170 
1171 		blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
1172 		if (!blob)
1173 			return -ENOMEM;
1174 
1175 		data.address = __psp_pa(blob);
1176 		data.len = params.len;
1177 	}
1178 
1179 cmd:
1180 	data.handle = to_kvm_sev_info(kvm)->handle;
1181 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, &data, &argp->error);
1182 
1183 	/*
1184 	 * If we query the session length, FW responded with expected data.
1185 	 */
1186 	if (!params.len)
1187 		goto done;
1188 
1189 	if (ret)
1190 		goto e_free_blob;
1191 
1192 	if (blob) {
1193 		if (copy_to_user(p, blob, params.len))
1194 			ret = -EFAULT;
1195 	}
1196 
1197 done:
1198 	params.len = data.len;
1199 	if (copy_to_user(measure, &params, sizeof(params)))
1200 		ret = -EFAULT;
1201 e_free_blob:
1202 	kfree(blob);
1203 	return ret;
1204 }
1205 
1206 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1207 {
1208 	struct sev_data_launch_finish data;
1209 
1210 	if (!sev_guest(kvm))
1211 		return -ENOTTY;
1212 
1213 	data.handle = to_kvm_sev_info(kvm)->handle;
1214 	return sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, &data, &argp->error);
1215 }
1216 
1217 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
1218 {
1219 	struct kvm_sev_guest_status params;
1220 	struct sev_data_guest_status data;
1221 	int ret;
1222 
1223 	if (!sev_guest(kvm))
1224 		return -ENOTTY;
1225 
1226 	memset(&data, 0, sizeof(data));
1227 
1228 	data.handle = to_kvm_sev_info(kvm)->handle;
1229 	ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, &data, &argp->error);
1230 	if (ret)
1231 		return ret;
1232 
1233 	params.policy = data.policy;
1234 	params.state = data.state;
1235 	params.handle = data.handle;
1236 
1237 	if (copy_to_user(u64_to_user_ptr(argp->data), &params, sizeof(params)))
1238 		ret = -EFAULT;
1239 
1240 	return ret;
1241 }
1242 
1243 static int sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src_pa,
1244 			     unsigned long dst_pa, unsigned int size,
1245 			     unsigned int ioctl, int *error)
1246 {
1247 	int cmd = ioctl == KVM_SEV_DBG_DECRYPT ? SEV_CMD_DBG_DECRYPT :
1248 						 SEV_CMD_DBG_ENCRYPT;
1249 	struct sev_data_dbg data = {
1250 		.handle = to_kvm_sev_info(kvm)->handle,
1251 		.dst_addr = dst_pa,
1252 		.src_addr = src_pa,
1253 		.len = size,
1254 	};
1255 
1256 	return sev_issue_cmd(kvm, cmd, &data, error);
1257 }
1258 
1259 static void *sev_dbg_crypt_slow_alloc(struct page *page, unsigned long __va,
1260 				      unsigned int len, unsigned long *pa,
1261 				      unsigned int *nr_bytes)
1262 {
1263 	unsigned long va = ALIGN_DOWN(__va, 16);
1264 
1265 	/* The number of bytes to {de,en}crypt must be 16-byte aligned. */
1266 	*nr_bytes = round_up(len, 16);
1267 
1268 	/*
1269 	 * Increase the number of bytes to {de,en}crypt by one chunk (16 bytes)
1270 	 * if the aligned address and length doesn't cover the unaligned range,
1271 	 * e.g. if the address is unaligned _and_ the access will split a chunk
1272 	 * at the tail.
1273 	 */
1274 	if (va + *nr_bytes < __va + len)
1275 		*nr_bytes += 16;
1276 
1277 	*pa = __sme_page_pa(page) + (va & ~PAGE_MASK);
1278 
1279 	/*
1280 	 * Sanity check that the new access won't split a page.  This should
1281 	 * never happen; just pretend the allocation failed.
1282 	 */
1283 	if (WARN_ON_ONCE((*pa & PAGE_MASK) != ((*pa + *nr_bytes - 1) & PAGE_MASK)))
1284 		return NULL;
1285 
1286 	/*
1287 	 * If SNP is enabled, i.e. the RMP is active, allocate a full page to
1288 	 * prevent concurrent accesses to the page.  As required by firmware,
1289 	 * the PSP driver updates the RMP to temporarily transfer ownership of
1290 	 * the page to Firmware while the {DE,EN}CRYPT operation is in-progress,
1291 	 * and so concurrent software accesses to the page will encounter
1292 	 * seemingly spurious RMP #PF violations
1293 	 */
1294 	if (cc_platform_has(CC_ATTR_HOST_SEV_SNP))
1295 		return (void *)__get_free_page(GFP_KERNEL);
1296 
1297 	return kmalloc(*nr_bytes, GFP_KERNEL);
1298 }
1299 
1300 static void sev_dbg_crypt_slow_free(void *buf)
1301 {
1302 	if (cc_platform_has(CC_ATTR_HOST_SEV_SNP))
1303 		free_page((unsigned long)buf);
1304 	else
1305 		kfree(buf);
1306 }
1307 
1308 static int sev_dbg_decrypt_slow(struct kvm *kvm, unsigned long src,
1309 				struct page *src_p, unsigned long dst,
1310 				unsigned int len, int *err)
1311 {
1312 	unsigned int nr_bytes;
1313 	unsigned long src_pa;
1314 	void *buf;
1315 	int r;
1316 
1317 	buf = sev_dbg_crypt_slow_alloc(src_p, src, len, &src_pa, &nr_bytes);
1318 	if (!buf)
1319 		return -ENOMEM;
1320 
1321 	r = sev_issue_dbg_cmd(kvm, src_pa, __sme_set(__pa(buf)),
1322 			      nr_bytes, KVM_SEV_DBG_DECRYPT, err);
1323 	if (r)
1324 		goto out;
1325 
1326 	if (copy_to_user((void __user *)dst, buf + (src & 15), len))
1327 		r = -EFAULT;
1328 out:
1329 	sev_dbg_crypt_slow_free(buf);
1330 	return r;
1331 }
1332 
1333 static int sev_dbg_encrypt_slow(struct kvm *kvm, unsigned long src,
1334 				unsigned long dst, struct page *dst_p,
1335 				unsigned int len, int *err)
1336 {
1337 	unsigned int nr_bytes;
1338 	unsigned long dst_pa;
1339 	void *buf;
1340 	int r;
1341 
1342 	/* Decrypt the _destination_ to do a RMW on plaintext. */
1343 	buf = sev_dbg_crypt_slow_alloc(dst_p, dst, len, &dst_pa, &nr_bytes);
1344 	if (!buf)
1345 		return -ENOMEM;
1346 
1347 	r = sev_issue_dbg_cmd(kvm, dst_pa, __sme_set(__pa(buf)),
1348 			      nr_bytes, KVM_SEV_DBG_DECRYPT, err);
1349 	if (r)
1350 		goto out;
1351 
1352 	/*
1353 	 * Copy from the source into the intermediate buffer, and then
1354 	 * re-encrypt the buffer into the destination.
1355 	 */
1356 	if (copy_from_user(buf + (dst & 15), (void __user *)src, len))
1357 		r = -EFAULT;
1358 	else
1359 		r = sev_issue_dbg_cmd(kvm, __sme_set(__pa(buf)), dst_pa,
1360 				      nr_bytes, KVM_SEV_DBG_ENCRYPT, err);
1361 out:
1362 	sev_dbg_crypt_slow_free(buf);
1363 	return r;
1364 }
1365 
1366 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp,
1367 			 unsigned int cmd)
1368 {
1369 	struct kvm_sev_dbg debug;
1370 	unsigned int i, len;
1371 
1372 	if (!sev_guest(kvm))
1373 		return -ENOTTY;
1374 
1375 	if (copy_from_user(&debug, u64_to_user_ptr(argp->data), sizeof(debug)))
1376 		return -EFAULT;
1377 
1378 	if (!debug.len || !debug.src_uaddr || !debug.dst_uaddr)
1379 		return -EINVAL;
1380 
1381 	if (debug.src_uaddr + debug.len < debug.src_uaddr ||
1382 	    debug.dst_uaddr + debug.len < debug.dst_uaddr)
1383 		return -EINVAL;
1384 
1385 	for (i = 0; i < debug.len; i += len) {
1386 		unsigned long src = debug.src_uaddr + i;
1387 		unsigned long dst = debug.dst_uaddr + i;
1388 		unsigned long s_off = src & ~PAGE_MASK;
1389 		unsigned long d_off = dst & ~PAGE_MASK;
1390 		struct page *src_p, *dst_p;
1391 		int ret;
1392 
1393 		/*
1394 		 * Copy as many remaining bytes as possible while staying in a
1395 		 * single page for both the source and destination.
1396 		 */
1397 		len = min3(debug.len - i, PAGE_SIZE - s_off, PAGE_SIZE - d_off);
1398 
1399 		/*
1400 		 * Pin the source and destination pages; firmware operates on
1401 		 * physical addresses.
1402 		 */
1403 		src_p = sev_pin_page(kvm, src & PAGE_MASK, 0);
1404 		if (IS_ERR(src_p))
1405 			return PTR_ERR(src_p);
1406 
1407 		dst_p = sev_pin_page(kvm, dst & PAGE_MASK, FOLL_WRITE);
1408 		if (IS_ERR(dst_p)) {
1409 			sev_unpin_page(kvm, src_p);
1410 			return PTR_ERR(dst_p);
1411 		}
1412 
1413 		/*
1414 		 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify
1415 		 * the pages; flush the destination too so that future accesses do not
1416 		 * see stale data.
1417 		 */
1418 		sev_clflush_pages(&src_p, 1);
1419 		sev_clflush_pages(&dst_p, 1);
1420 
1421 		if (IS_ALIGNED(src, 16) && IS_ALIGNED(dst, 16) && IS_ALIGNED(len, 16))
1422 			ret = sev_issue_dbg_cmd(kvm,
1423 						__sme_page_pa(src_p) + s_off,
1424 						__sme_page_pa(dst_p) + d_off,
1425 						len, cmd, &argp->error);
1426 		else if (cmd == KVM_SEV_DBG_DECRYPT)
1427 			ret = sev_dbg_decrypt_slow(kvm, src, src_p, dst,
1428 						   len, &argp->error);
1429 		else
1430 			ret = sev_dbg_encrypt_slow(kvm, src, dst, dst_p,
1431 						   len, &argp->error);
1432 
1433 		sev_unpin_page(kvm, src_p);
1434 		sev_unpin_page(kvm, dst_p);
1435 
1436 		if (ret)
1437 			return ret;
1438 	}
1439 	return 0;
1440 }
1441 
1442 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
1443 {
1444 	struct sev_data_launch_secret data;
1445 	struct kvm_sev_launch_secret params;
1446 	struct page **pages;
1447 	void *blob, *hdr;
1448 	unsigned long n, i;
1449 	int ret, offset;
1450 
1451 	if (!sev_guest(kvm))
1452 		return -ENOTTY;
1453 
1454 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
1455 		return -EFAULT;
1456 
1457 	pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, FOLL_WRITE);
1458 	if (IS_ERR(pages))
1459 		return PTR_ERR(pages);
1460 
1461 	/*
1462 	 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in
1463 	 * place; the cache may contain the data that was written unencrypted.
1464 	 */
1465 	sev_clflush_pages(pages, n);
1466 
1467 	/*
1468 	 * The secret must be copied into contiguous memory region, lets verify
1469 	 * that userspace memory pages are contiguous before we issue command.
1470 	 */
1471 	if (get_num_contig_pages(0, pages, n) != n) {
1472 		ret = -EINVAL;
1473 		goto e_unpin_memory;
1474 	}
1475 
1476 	memset(&data, 0, sizeof(data));
1477 
1478 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1479 	data.guest_address = __sme_page_pa(pages[0]) + offset;
1480 	data.guest_len = params.guest_len;
1481 
1482 	blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1483 	if (IS_ERR(blob)) {
1484 		ret = PTR_ERR(blob);
1485 		goto e_unpin_memory;
1486 	}
1487 
1488 	data.trans_address = __psp_pa(blob);
1489 	data.trans_len = params.trans_len;
1490 
1491 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1492 	if (IS_ERR(hdr)) {
1493 		ret = PTR_ERR(hdr);
1494 		goto e_free_blob;
1495 	}
1496 	data.hdr_address = __psp_pa(hdr);
1497 	data.hdr_len = params.hdr_len;
1498 
1499 	data.handle = to_kvm_sev_info(kvm)->handle;
1500 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, &data, &argp->error);
1501 
1502 	kfree(hdr);
1503 
1504 e_free_blob:
1505 	kfree(blob);
1506 e_unpin_memory:
1507 	/* content of memory is updated, mark pages dirty */
1508 	for (i = 0; i < n; i++) {
1509 		set_page_dirty_lock(pages[i]);
1510 		mark_page_accessed(pages[i]);
1511 	}
1512 	sev_unpin_memory(kvm, pages, n);
1513 	return ret;
1514 }
1515 
1516 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp)
1517 {
1518 	void __user *report = u64_to_user_ptr(argp->data);
1519 	struct sev_data_attestation_report data;
1520 	struct kvm_sev_attestation_report params;
1521 	void __user *p;
1522 	void *blob = NULL;
1523 	int ret;
1524 
1525 	if (!sev_guest(kvm))
1526 		return -ENOTTY;
1527 
1528 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
1529 		return -EFAULT;
1530 
1531 	memset(&data, 0, sizeof(data));
1532 
1533 	/* User wants to query the blob length */
1534 	if (!params.len)
1535 		goto cmd;
1536 
1537 	p = u64_to_user_ptr(params.uaddr);
1538 	if (p) {
1539 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
1540 			return -EINVAL;
1541 
1542 		blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
1543 		if (!blob)
1544 			return -ENOMEM;
1545 
1546 		data.address = __psp_pa(blob);
1547 		data.len = params.len;
1548 		memcpy(data.mnonce, params.mnonce, sizeof(params.mnonce));
1549 	}
1550 cmd:
1551 	data.handle = to_kvm_sev_info(kvm)->handle;
1552 	ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, &data, &argp->error);
1553 	/*
1554 	 * If we query the session length, FW responded with expected data.
1555 	 */
1556 	if (!params.len)
1557 		goto done;
1558 
1559 	if (ret)
1560 		goto e_free_blob;
1561 
1562 	if (blob) {
1563 		if (copy_to_user(p, blob, params.len))
1564 			ret = -EFAULT;
1565 	}
1566 
1567 done:
1568 	params.len = data.len;
1569 	if (copy_to_user(report, &params, sizeof(params)))
1570 		ret = -EFAULT;
1571 e_free_blob:
1572 	kfree(blob);
1573 	return ret;
1574 }
1575 
1576 /* Userspace wants to query session length. */
1577 static int
1578 __sev_send_start_query_session_length(struct kvm *kvm, struct kvm_sev_cmd *argp,
1579 				      struct kvm_sev_send_start *params)
1580 {
1581 	struct sev_data_send_start data;
1582 	int ret;
1583 
1584 	memset(&data, 0, sizeof(data));
1585 	data.handle = to_kvm_sev_info(kvm)->handle;
1586 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1587 
1588 	params->session_len = data.session_len;
1589 	if (copy_to_user(u64_to_user_ptr(argp->data), params,
1590 				sizeof(struct kvm_sev_send_start)))
1591 		ret = -EFAULT;
1592 
1593 	return ret;
1594 }
1595 
1596 static int sev_send_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1597 {
1598 	struct sev_data_send_start data;
1599 	struct kvm_sev_send_start params;
1600 	void *amd_certs, *session_data;
1601 	void *pdh_cert, *plat_certs;
1602 	int ret;
1603 
1604 	if (!sev_guest(kvm))
1605 		return -ENOTTY;
1606 
1607 	if (copy_from_user(&params, u64_to_user_ptr(argp->data),
1608 				sizeof(struct kvm_sev_send_start)))
1609 		return -EFAULT;
1610 
1611 	/* if session_len is zero, userspace wants to query the session length */
1612 	if (!params.session_len)
1613 		return __sev_send_start_query_session_length(kvm, argp,
1614 				&params);
1615 
1616 	/* some sanity checks */
1617 	if (!params.pdh_cert_uaddr || !params.pdh_cert_len ||
1618 	    !params.session_uaddr || params.session_len > SEV_FW_BLOB_MAX_SIZE)
1619 		return -EINVAL;
1620 
1621 	/* allocate the memory to hold the session data blob */
1622 	session_data = kzalloc(params.session_len, GFP_KERNEL_ACCOUNT);
1623 	if (!session_data)
1624 		return -ENOMEM;
1625 
1626 	/* copy the certificate blobs from userspace */
1627 	pdh_cert = psp_copy_user_blob(params.pdh_cert_uaddr,
1628 				params.pdh_cert_len);
1629 	if (IS_ERR(pdh_cert)) {
1630 		ret = PTR_ERR(pdh_cert);
1631 		goto e_free_session;
1632 	}
1633 
1634 	plat_certs = psp_copy_user_blob(params.plat_certs_uaddr,
1635 				params.plat_certs_len);
1636 	if (IS_ERR(plat_certs)) {
1637 		ret = PTR_ERR(plat_certs);
1638 		goto e_free_pdh;
1639 	}
1640 
1641 	amd_certs = psp_copy_user_blob(params.amd_certs_uaddr,
1642 				params.amd_certs_len);
1643 	if (IS_ERR(amd_certs)) {
1644 		ret = PTR_ERR(amd_certs);
1645 		goto e_free_plat_cert;
1646 	}
1647 
1648 	/* populate the FW SEND_START field with system physical address */
1649 	memset(&data, 0, sizeof(data));
1650 	data.pdh_cert_address = __psp_pa(pdh_cert);
1651 	data.pdh_cert_len = params.pdh_cert_len;
1652 	data.plat_certs_address = __psp_pa(plat_certs);
1653 	data.plat_certs_len = params.plat_certs_len;
1654 	data.amd_certs_address = __psp_pa(amd_certs);
1655 	data.amd_certs_len = params.amd_certs_len;
1656 	data.session_address = __psp_pa(session_data);
1657 	data.session_len = params.session_len;
1658 	data.handle = to_kvm_sev_info(kvm)->handle;
1659 
1660 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1661 
1662 	if (!ret && copy_to_user(u64_to_user_ptr(params.session_uaddr),
1663 			session_data, params.session_len)) {
1664 		ret = -EFAULT;
1665 		goto e_free_amd_cert;
1666 	}
1667 
1668 	params.policy = data.policy;
1669 	params.session_len = data.session_len;
1670 	if (copy_to_user(u64_to_user_ptr(argp->data), &params,
1671 				sizeof(struct kvm_sev_send_start)))
1672 		ret = -EFAULT;
1673 
1674 e_free_amd_cert:
1675 	kfree(amd_certs);
1676 e_free_plat_cert:
1677 	kfree(plat_certs);
1678 e_free_pdh:
1679 	kfree(pdh_cert);
1680 e_free_session:
1681 	kfree(session_data);
1682 	return ret;
1683 }
1684 
1685 /* Userspace wants to query either header or trans length. */
1686 static int
1687 __sev_send_update_data_query_lengths(struct kvm *kvm, struct kvm_sev_cmd *argp,
1688 				     struct kvm_sev_send_update_data *params)
1689 {
1690 	struct sev_data_send_update_data data;
1691 	int ret;
1692 
1693 	memset(&data, 0, sizeof(data));
1694 	data.handle = to_kvm_sev_info(kvm)->handle;
1695 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1696 
1697 	params->hdr_len = data.hdr_len;
1698 	params->trans_len = data.trans_len;
1699 
1700 	if (copy_to_user(u64_to_user_ptr(argp->data), params,
1701 			 sizeof(struct kvm_sev_send_update_data)))
1702 		ret = -EFAULT;
1703 
1704 	return ret;
1705 }
1706 
1707 static int sev_send_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1708 {
1709 	struct sev_data_send_update_data data;
1710 	struct kvm_sev_send_update_data params;
1711 	void *hdr, *trans_data;
1712 	struct page *guest_page;
1713 	int ret, offset;
1714 
1715 	if (!sev_guest(kvm))
1716 		return -ENOTTY;
1717 
1718 	if (copy_from_user(&params, u64_to_user_ptr(argp->data),
1719 			sizeof(struct kvm_sev_send_update_data)))
1720 		return -EFAULT;
1721 
1722 	/* userspace wants to query either header or trans length */
1723 	if (!params.trans_len || !params.hdr_len)
1724 		return __sev_send_update_data_query_lengths(kvm, argp, &params);
1725 
1726 	if (!params.trans_uaddr || !params.guest_uaddr ||
1727 	    !params.guest_len || !params.hdr_uaddr)
1728 		return -EINVAL;
1729 
1730 	/* Check if we are crossing the page boundary */
1731 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1732 	if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1733 		return -EINVAL;
1734 
1735 	/* Pin guest memory */
1736 	guest_page = sev_pin_page(kvm, params.guest_uaddr & PAGE_MASK, 0);
1737 	if (IS_ERR(guest_page))
1738 		return PTR_ERR(guest_page);
1739 
1740 	/* allocate memory for header and transport buffer */
1741 	ret = -ENOMEM;
1742 	hdr = kzalloc(params.hdr_len, GFP_KERNEL);
1743 	if (!hdr)
1744 		goto e_unpin;
1745 
1746 	trans_data = kzalloc(params.trans_len, GFP_KERNEL);
1747 	if (!trans_data)
1748 		goto e_free_hdr;
1749 
1750 	memset(&data, 0, sizeof(data));
1751 	data.hdr_address = __psp_pa(hdr);
1752 	data.hdr_len = params.hdr_len;
1753 	data.trans_address = __psp_pa(trans_data);
1754 	data.trans_len = params.trans_len;
1755 
1756 	/* The SEND_UPDATE_DATA command requires C-bit to be always set. */
1757 	data.guest_address = page_to_phys(guest_page) + offset;
1758 	data.guest_address |= sev_me_mask;
1759 	data.guest_len = params.guest_len;
1760 	data.handle = to_kvm_sev_info(kvm)->handle;
1761 
1762 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1763 
1764 	if (ret)
1765 		goto e_free_trans_data;
1766 
1767 	/* copy transport buffer to user space */
1768 	if (copy_to_user(u64_to_user_ptr(params.trans_uaddr),
1769 			 trans_data, params.trans_len)) {
1770 		ret = -EFAULT;
1771 		goto e_free_trans_data;
1772 	}
1773 
1774 	/* Copy packet header to userspace. */
1775 	if (copy_to_user(u64_to_user_ptr(params.hdr_uaddr), hdr,
1776 			 params.hdr_len))
1777 		ret = -EFAULT;
1778 
1779 e_free_trans_data:
1780 	kfree(trans_data);
1781 e_free_hdr:
1782 	kfree(hdr);
1783 e_unpin:
1784 	sev_unpin_page(kvm, guest_page);
1785 	return ret;
1786 }
1787 
1788 static int sev_send_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1789 {
1790 	struct sev_data_send_finish data;
1791 
1792 	if (!sev_guest(kvm))
1793 		return -ENOTTY;
1794 
1795 	data.handle = to_kvm_sev_info(kvm)->handle;
1796 	return sev_issue_cmd(kvm, SEV_CMD_SEND_FINISH, &data, &argp->error);
1797 }
1798 
1799 static int sev_send_cancel(struct kvm *kvm, struct kvm_sev_cmd *argp)
1800 {
1801 	struct sev_data_send_cancel data;
1802 
1803 	if (!sev_guest(kvm))
1804 		return -ENOTTY;
1805 
1806 	data.handle = to_kvm_sev_info(kvm)->handle;
1807 	return sev_issue_cmd(kvm, SEV_CMD_SEND_CANCEL, &data, &argp->error);
1808 }
1809 
1810 static int sev_receive_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1811 {
1812 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
1813 	struct sev_data_receive_start start;
1814 	struct kvm_sev_receive_start params;
1815 	int *error = &argp->error;
1816 	void *session_data;
1817 	void *pdh_data;
1818 	int ret;
1819 
1820 	if (!sev_guest(kvm))
1821 		return -ENOTTY;
1822 
1823 	/* Get parameter from the userspace */
1824 	if (copy_from_user(&params, u64_to_user_ptr(argp->data),
1825 			sizeof(struct kvm_sev_receive_start)))
1826 		return -EFAULT;
1827 
1828 	/* some sanity checks */
1829 	if (!params.pdh_uaddr || !params.pdh_len ||
1830 	    !params.session_uaddr || !params.session_len)
1831 		return -EINVAL;
1832 
1833 	pdh_data = psp_copy_user_blob(params.pdh_uaddr, params.pdh_len);
1834 	if (IS_ERR(pdh_data))
1835 		return PTR_ERR(pdh_data);
1836 
1837 	session_data = psp_copy_user_blob(params.session_uaddr,
1838 			params.session_len);
1839 	if (IS_ERR(session_data)) {
1840 		ret = PTR_ERR(session_data);
1841 		goto e_free_pdh;
1842 	}
1843 
1844 	memset(&start, 0, sizeof(start));
1845 	start.handle = params.handle;
1846 	start.policy = params.policy;
1847 	start.pdh_cert_address = __psp_pa(pdh_data);
1848 	start.pdh_cert_len = params.pdh_len;
1849 	start.session_address = __psp_pa(session_data);
1850 	start.session_len = params.session_len;
1851 
1852 	/* create memory encryption context */
1853 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_RECEIVE_START, &start,
1854 				error);
1855 	if (ret)
1856 		goto e_free_session;
1857 
1858 	/* Bind ASID to this guest */
1859 	ret = sev_bind_asid(kvm, start.handle, error);
1860 	if (ret) {
1861 		sev_decommission(start.handle);
1862 		goto e_free_session;
1863 	}
1864 
1865 	params.handle = start.handle;
1866 	if (copy_to_user(u64_to_user_ptr(argp->data),
1867 			 &params, sizeof(struct kvm_sev_receive_start))) {
1868 		ret = -EFAULT;
1869 		sev_unbind_asid(kvm, start.handle);
1870 		goto e_free_session;
1871 	}
1872 
1873     	sev->handle = start.handle;
1874 	sev->fd = argp->sev_fd;
1875 
1876 e_free_session:
1877 	kfree(session_data);
1878 e_free_pdh:
1879 	kfree(pdh_data);
1880 
1881 	return ret;
1882 }
1883 
1884 static int sev_receive_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1885 {
1886 	struct kvm_sev_receive_update_data params;
1887 	struct sev_data_receive_update_data data;
1888 	void *hdr = NULL, *trans = NULL;
1889 	struct page *guest_page;
1890 	int ret, offset;
1891 
1892 	if (!sev_guest(kvm))
1893 		return -EINVAL;
1894 
1895 	if (copy_from_user(&params, u64_to_user_ptr(argp->data),
1896 			sizeof(struct kvm_sev_receive_update_data)))
1897 		return -EFAULT;
1898 
1899 	if (!params.hdr_uaddr || !params.hdr_len ||
1900 	    !params.guest_uaddr || !params.guest_len ||
1901 	    !params.trans_uaddr || !params.trans_len)
1902 		return -EINVAL;
1903 
1904 	/* Check if we are crossing the page boundary */
1905 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1906 	if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1907 		return -EINVAL;
1908 
1909 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1910 	if (IS_ERR(hdr))
1911 		return PTR_ERR(hdr);
1912 
1913 	trans = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1914 	if (IS_ERR(trans)) {
1915 		ret = PTR_ERR(trans);
1916 		goto e_free_hdr;
1917 	}
1918 
1919 	memset(&data, 0, sizeof(data));
1920 	data.hdr_address = __psp_pa(hdr);
1921 	data.hdr_len = params.hdr_len;
1922 	data.trans_address = __psp_pa(trans);
1923 	data.trans_len = params.trans_len;
1924 
1925 	/* Pin guest memory */
1926 	guest_page = sev_pin_page(kvm, params.guest_uaddr & PAGE_MASK, FOLL_WRITE);
1927 	if (IS_ERR(guest_page)) {
1928 		ret = PTR_ERR(guest_page);
1929 		goto e_free_trans;
1930 	}
1931 
1932 	/*
1933 	 * Flush (on non-coherent CPUs) before RECEIVE_UPDATE_DATA, the PSP
1934 	 * encrypts the written data with the guest's key, and the cache may
1935 	 * contain dirty, unencrypted data.
1936 	 */
1937 	sev_clflush_pages(&guest_page, 1);
1938 
1939 	/* The RECEIVE_UPDATE_DATA command requires C-bit to be always set. */
1940 	data.guest_address = page_to_phys(guest_page) + offset;
1941 	data.guest_address |= sev_me_mask;
1942 	data.guest_len = params.guest_len;
1943 	data.handle = to_kvm_sev_info(kvm)->handle;
1944 
1945 	ret = sev_issue_cmd(kvm, SEV_CMD_RECEIVE_UPDATE_DATA, &data,
1946 				&argp->error);
1947 
1948 	sev_unpin_page(kvm, guest_page);
1949 
1950 e_free_trans:
1951 	kfree(trans);
1952 e_free_hdr:
1953 	kfree(hdr);
1954 
1955 	return ret;
1956 }
1957 
1958 static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1959 {
1960 	struct sev_data_receive_finish data;
1961 
1962 	if (!sev_guest(kvm))
1963 		return -ENOTTY;
1964 
1965 	data.handle = to_kvm_sev_info(kvm)->handle;
1966 	return sev_issue_cmd(kvm, SEV_CMD_RECEIVE_FINISH, &data, &argp->error);
1967 }
1968 
1969 static bool is_cmd_allowed_from_mirror(u32 cmd_id)
1970 {
1971 	/*
1972 	 * Allow mirrors VM to call KVM_SEV_LAUNCH_UPDATE_VMSA to enable SEV-ES
1973 	 * active mirror VMs. Also allow the debugging and status commands.
1974 	 */
1975 	if (cmd_id == KVM_SEV_LAUNCH_UPDATE_VMSA ||
1976 	    cmd_id == KVM_SEV_GUEST_STATUS || cmd_id == KVM_SEV_DBG_DECRYPT ||
1977 	    cmd_id == KVM_SEV_DBG_ENCRYPT)
1978 		return true;
1979 
1980 	return false;
1981 }
1982 
1983 static int sev_lock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1984 {
1985 	struct kvm_sev_info *dst_sev = to_kvm_sev_info(dst_kvm);
1986 	struct kvm_sev_info *src_sev = to_kvm_sev_info(src_kvm);
1987 	int r = -EBUSY;
1988 
1989 	if (dst_kvm == src_kvm)
1990 		return -EINVAL;
1991 
1992 	/*
1993 	 * Bail if these VMs are already involved in a migration to avoid
1994 	 * deadlock between two VMs trying to migrate to/from each other.
1995 	 */
1996 	if (atomic_cmpxchg_acquire(&dst_sev->migration_in_progress, 0, 1))
1997 		return -EBUSY;
1998 
1999 	if (atomic_cmpxchg_acquire(&src_sev->migration_in_progress, 0, 1))
2000 		goto release_dst;
2001 
2002 	r = -EINTR;
2003 	if (mutex_lock_killable(&dst_kvm->lock))
2004 		goto release_src;
2005 	if (mutex_lock_killable_nested(&src_kvm->lock, SINGLE_DEPTH_NESTING))
2006 		goto unlock_dst;
2007 	return 0;
2008 
2009 unlock_dst:
2010 	mutex_unlock(&dst_kvm->lock);
2011 release_src:
2012 	atomic_set_release(&src_sev->migration_in_progress, 0);
2013 release_dst:
2014 	atomic_set_release(&dst_sev->migration_in_progress, 0);
2015 	return r;
2016 }
2017 
2018 static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
2019 {
2020 	struct kvm_sev_info *dst_sev = to_kvm_sev_info(dst_kvm);
2021 	struct kvm_sev_info *src_sev = to_kvm_sev_info(src_kvm);
2022 
2023 	mutex_unlock(&dst_kvm->lock);
2024 	mutex_unlock(&src_kvm->lock);
2025 	atomic_set_release(&dst_sev->migration_in_progress, 0);
2026 	atomic_set_release(&src_sev->migration_in_progress, 0);
2027 }
2028 
2029 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
2030 {
2031 	struct kvm_sev_info *dst = to_kvm_sev_info(dst_kvm);
2032 	struct kvm_sev_info *src = to_kvm_sev_info(src_kvm);
2033 	struct kvm_vcpu *dst_vcpu, *src_vcpu;
2034 	struct vcpu_svm *dst_svm, *src_svm;
2035 	struct kvm_sev_info *mirror;
2036 	unsigned long i;
2037 
2038 	dst->active = true;
2039 	dst->asid = src->asid;
2040 	dst->handle = src->handle;
2041 	dst->pages_locked = src->pages_locked;
2042 	dst->es_active = src->es_active;
2043 	dst->vmsa_features = src->vmsa_features;
2044 
2045 	src->asid = 0;
2046 	src->active = false;
2047 	src->handle = 0;
2048 	src->pages_locked = 0;
2049 	src->es_active = false;
2050 
2051 	list_cut_before(&dst->regions_list, &src->regions_list, &src->regions_list);
2052 
2053 	mutex_lock(&sev_mirror_lock);
2054 
2055 	/*
2056 	 * If this VM has mirrors, "transfer" each mirror's refcount of the
2057 	 * source to the destination (this KVM).  The caller holds a reference
2058 	 * to the source, so there's no danger of use-after-free.
2059 	 */
2060 	list_cut_before(&dst->mirror_vms, &src->mirror_vms, &src->mirror_vms);
2061 	list_for_each_entry(mirror, &dst->mirror_vms, mirror_entry) {
2062 		kvm_get_kvm(dst_kvm);
2063 		kvm_put_kvm(src_kvm);
2064 		mirror->enc_context_owner = dst_kvm;
2065 	}
2066 
2067 	/*
2068 	 * If this VM is a mirror, remove the old mirror from the owners list
2069 	 * and add the new mirror to the list.
2070 	 */
2071 	if (is_mirroring_enc_context(src_kvm)) {
2072 		struct kvm_sev_info *owner_sev_info = to_kvm_sev_info(src->enc_context_owner);
2073 
2074 		dst->enc_context_owner = src->enc_context_owner;
2075 		src->enc_context_owner = NULL;
2076 		list_del(&src->mirror_entry);
2077 		list_add_tail(&dst->mirror_entry, &owner_sev_info->mirror_vms);
2078 	}
2079 	mutex_unlock(&sev_mirror_lock);
2080 
2081 	kvm_for_each_vcpu(i, dst_vcpu, dst_kvm) {
2082 		dst_svm = to_svm(dst_vcpu);
2083 
2084 		sev_init_vmcb(dst_svm, false);
2085 
2086 		if (!dst->es_active)
2087 			continue;
2088 
2089 		/*
2090 		 * Note, the source is not required to have the same number of
2091 		 * vCPUs as the destination when migrating a vanilla SEV VM.
2092 		 */
2093 		src_vcpu = kvm_get_vcpu(src_kvm, i);
2094 		src_svm = to_svm(src_vcpu);
2095 
2096 		/*
2097 		 * Transfer VMSA and GHCB state to the destination.  Nullify and
2098 		 * clear source fields as appropriate, the state now belongs to
2099 		 * the destination.
2100 		 */
2101 		memcpy(&dst_svm->sev_es, &src_svm->sev_es, sizeof(src_svm->sev_es));
2102 		dst_svm->vmcb->control.ghcb_gpa = src_svm->vmcb->control.ghcb_gpa;
2103 		dst_svm->vmcb->control.vmsa_pa = src_svm->vmcb->control.vmsa_pa;
2104 		dst_vcpu->arch.guest_state_protected = true;
2105 
2106 		memset(&src_svm->sev_es, 0, sizeof(src_svm->sev_es));
2107 		src_svm->vmcb->control.ghcb_gpa = INVALID_PAGE;
2108 		src_svm->vmcb->control.vmsa_pa = INVALID_PAGE;
2109 		src_vcpu->arch.guest_state_protected = false;
2110 	}
2111 }
2112 
2113 static int sev_check_source_vcpus(struct kvm *dst, struct kvm *src)
2114 {
2115 	struct kvm_vcpu *src_vcpu;
2116 	unsigned long i;
2117 
2118 	if (kvm_is_vcpu_creation_in_progress(src) ||
2119 	    kvm_is_vcpu_creation_in_progress(dst))
2120 		return -EBUSY;
2121 
2122 	if (!sev_es_guest(src))
2123 		return 0;
2124 
2125 	if (atomic_read(&src->online_vcpus) != atomic_read(&dst->online_vcpus))
2126 		return -EINVAL;
2127 
2128 	kvm_for_each_vcpu(i, src_vcpu, src) {
2129 		if (!src_vcpu->arch.guest_state_protected)
2130 			return -EINVAL;
2131 	}
2132 
2133 	return 0;
2134 }
2135 
2136 int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2137 {
2138 	struct kvm_sev_info *dst_sev = to_kvm_sev_info(kvm);
2139 	struct kvm_sev_info *src_sev, *cg_cleanup_sev;
2140 	CLASS(fd, f)(source_fd);
2141 	struct kvm *source_kvm;
2142 	bool charged = false;
2143 	int ret;
2144 
2145 	if (fd_empty(f))
2146 		return -EBADF;
2147 
2148 	if (!file_is_kvm(fd_file(f)))
2149 		return -EBADF;
2150 
2151 	source_kvm = fd_file(f)->private_data;
2152 	ret = sev_lock_two_vms(kvm, source_kvm);
2153 	if (ret)
2154 		return ret;
2155 
2156 	/* Do not allow SNP VM migration until additional state transfer is implemented  */
2157 	if (kvm->arch.vm_type != source_kvm->arch.vm_type ||
2158 	    sev_guest(kvm) || !sev_guest(source_kvm) || sev_snp_guest(source_kvm)) {
2159 		ret = -EINVAL;
2160 		goto out_unlock;
2161 	}
2162 
2163 	src_sev = to_kvm_sev_info(source_kvm);
2164 
2165 	dst_sev->misc_cg = get_current_misc_cg();
2166 	cg_cleanup_sev = dst_sev;
2167 	if (dst_sev->misc_cg != src_sev->misc_cg) {
2168 		ret = sev_misc_cg_try_charge(dst_sev);
2169 		if (ret)
2170 			goto out_dst_cgroup;
2171 		charged = true;
2172 	}
2173 
2174 	ret = kvm_lock_all_vcpus(kvm);
2175 	if (ret)
2176 		goto out_dst_cgroup;
2177 	ret = kvm_lock_all_vcpus(source_kvm);
2178 	if (ret)
2179 		goto out_dst_vcpu;
2180 
2181 	ret = sev_check_source_vcpus(kvm, source_kvm);
2182 	if (ret)
2183 		goto out_source_vcpu;
2184 
2185 	/*
2186 	 * Allocate a new have_run_cpus for the destination, i.e. don't copy
2187 	 * the set of CPUs from the source.  If a CPU was used to run a vCPU in
2188 	 * the source VM but is never used for the destination VM, then the CPU
2189 	 * can only have cached memory that was accessible to the source VM.
2190 	 */
2191 	if (!zalloc_cpumask_var(&dst_sev->have_run_cpus, GFP_KERNEL_ACCOUNT)) {
2192 		ret = -ENOMEM;
2193 		goto out_source_vcpu;
2194 	}
2195 
2196 	sev_migrate_from(kvm, source_kvm);
2197 	kvm_vm_dead(source_kvm);
2198 	cg_cleanup_sev = src_sev;
2199 	ret = 0;
2200 
2201 out_source_vcpu:
2202 	kvm_unlock_all_vcpus(source_kvm);
2203 out_dst_vcpu:
2204 	kvm_unlock_all_vcpus(kvm);
2205 out_dst_cgroup:
2206 	/* Operates on the source on success, on the destination on failure.  */
2207 	if (charged)
2208 		sev_misc_cg_uncharge(cg_cleanup_sev);
2209 	put_misc_cg(cg_cleanup_sev->misc_cg);
2210 	cg_cleanup_sev->misc_cg = NULL;
2211 out_unlock:
2212 	sev_unlock_two_vms(kvm, source_kvm);
2213 	return ret;
2214 }
2215 
2216 int sev_dev_get_attr(u32 group, u64 attr, u64 *val)
2217 {
2218 	if (group != KVM_X86_GRP_SEV)
2219 		return -ENXIO;
2220 
2221 	switch (attr) {
2222 	case KVM_X86_SEV_VMSA_FEATURES:
2223 		*val = sev_supported_vmsa_features;
2224 		return 0;
2225 
2226 	case KVM_X86_SNP_POLICY_BITS:
2227 		*val = snp_supported_policy_bits;
2228 		return 0;
2229 
2230 	case KVM_X86_SEV_SNP_REQ_CERTS:
2231 		*val = sev_snp_enabled ? 1 : 0;
2232 		return 0;
2233 	default:
2234 		return -ENXIO;
2235 	}
2236 }
2237 
2238 /*
2239  * The guest context contains all the information, keys and metadata
2240  * associated with the guest that the firmware tracks to implement SEV
2241  * and SNP features. The firmware stores the guest context in hypervisor
2242  * provide page via the SNP_GCTX_CREATE command.
2243  */
2244 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
2245 {
2246 	struct sev_data_snp_addr data = {};
2247 	void *context;
2248 	int rc;
2249 
2250 	/* Allocate memory for context page */
2251 	context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
2252 	if (!context)
2253 		return NULL;
2254 
2255 	data.address = __psp_pa(context);
2256 	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
2257 	if (rc) {
2258 		pr_warn("Failed to create SEV-SNP context, rc %d fw_error %d",
2259 			rc, argp->error);
2260 		snp_free_firmware_page(context);
2261 		return NULL;
2262 	}
2263 
2264 	return context;
2265 }
2266 
2267 static int snp_bind_asid(struct kvm *kvm, int *error)
2268 {
2269 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2270 	struct sev_data_snp_activate data = {0};
2271 
2272 	data.gctx_paddr = __psp_pa(sev->snp_context);
2273 	data.asid = sev_get_asid(kvm);
2274 	return sev_issue_cmd(kvm, SEV_CMD_SNP_ACTIVATE, &data, error);
2275 }
2276 
2277 static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
2278 {
2279 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2280 	struct sev_data_snp_launch_start start = {0};
2281 	struct kvm_sev_snp_launch_start params;
2282 	int rc;
2283 
2284 	if (!sev_snp_guest(kvm))
2285 		return -ENOTTY;
2286 
2287 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
2288 		return -EFAULT;
2289 
2290 	/* Don't allow userspace to allocate memory for more than 1 SNP context. */
2291 	if (sev->snp_context)
2292 		return -EINVAL;
2293 
2294 	if (params.flags)
2295 		return -EINVAL;
2296 
2297 	if (params.policy & ~snp_supported_policy_bits)
2298 		return -EINVAL;
2299 
2300 	/* Check for policy bits that must be set */
2301 	if (!(params.policy & SNP_POLICY_MASK_RSVD_MBO))
2302 		return -EINVAL;
2303 
2304 	if (snp_is_secure_tsc_enabled(kvm)) {
2305 		if (WARN_ON_ONCE(!kvm->arch.default_tsc_khz))
2306 			return -EINVAL;
2307 
2308 		start.desired_tsc_khz = kvm->arch.default_tsc_khz;
2309 	}
2310 
2311 	sev->snp_context = snp_context_create(kvm, argp);
2312 	if (!sev->snp_context)
2313 		return -ENOTTY;
2314 
2315 	start.gctx_paddr = __psp_pa(sev->snp_context);
2316 	start.policy = params.policy;
2317 
2318 	memcpy(start.gosvw, params.gosvw, sizeof(params.gosvw));
2319 	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_START, &start, &argp->error);
2320 	if (rc) {
2321 		pr_debug("%s: SEV_CMD_SNP_LAUNCH_START firmware command failed, rc %d\n",
2322 			 __func__, rc);
2323 		goto e_free_context;
2324 	}
2325 
2326 	sev->policy = params.policy;
2327 	sev->fd = argp->sev_fd;
2328 	rc = snp_bind_asid(kvm, &argp->error);
2329 	if (rc) {
2330 		pr_debug("%s: Failed to bind ASID to SEV-SNP context, rc %d\n",
2331 			 __func__, rc);
2332 		goto e_free_context;
2333 	}
2334 
2335 	return 0;
2336 
2337 e_free_context:
2338 	snp_decommission_context(kvm);
2339 
2340 	return rc;
2341 }
2342 
2343 struct sev_gmem_populate_args {
2344 	__u8 type;
2345 	int sev_fd;
2346 	int fw_error;
2347 };
2348 
2349 static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
2350 				  struct page *src_page, void *opaque)
2351 {
2352 	struct sev_gmem_populate_args *sev_populate_args = opaque;
2353 	struct sev_data_snp_launch_update fw_args = {0};
2354 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2355 	bool assigned = false;
2356 	int level;
2357 	int ret;
2358 
2359 	ret = snp_lookup_rmpentry((u64)pfn, &assigned, &level);
2360 	if (ret || assigned) {
2361 		pr_debug("%s: Failed to ensure GFN 0x%llx RMP entry is initial shared state, ret: %d assigned: %d\n",
2362 			 __func__, gfn, ret, assigned);
2363 		ret = ret ? -EINVAL : -EEXIST;
2364 		goto out;
2365 	}
2366 
2367 	if (src_page) {
2368 		void *src_vaddr = kmap_local_page(src_page);
2369 		void *dst_vaddr = kmap_local_pfn(pfn);
2370 
2371 		memcpy(dst_vaddr, src_vaddr, PAGE_SIZE);
2372 
2373 		kunmap_local(dst_vaddr);
2374 		kunmap_local(src_vaddr);
2375 	}
2376 
2377 	ret = rmp_make_private(pfn, gfn << PAGE_SHIFT, PG_LEVEL_4K,
2378 			       sev_get_asid(kvm), true);
2379 	if (ret)
2380 		goto out;
2381 
2382 	fw_args.gctx_paddr = __psp_pa(sev->snp_context);
2383 	fw_args.address = __sme_set(pfn_to_hpa(pfn));
2384 	fw_args.page_size = PG_LEVEL_TO_RMP(PG_LEVEL_4K);
2385 	fw_args.page_type = sev_populate_args->type;
2386 
2387 	ret = __sev_issue_cmd(sev_populate_args->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
2388 			      &fw_args, &sev_populate_args->fw_error);
2389 	/*
2390 	 * If the firmware command failed handle the reclaim and cleanup of that
2391 	 * PFN before reporting an error.
2392 	 *
2393 	 * Additionally, when invalid CPUID function entries are detected,
2394 	 * firmware writes the expected values into the page and leaves it
2395 	 * unencrypted so it can be used for debugging and error-reporting.
2396 	 *
2397 	 * Copy this page back into the source buffer so userspace can use this
2398 	 * information to provide information on which CPUID leaves/fields
2399 	 * failed CPUID validation.
2400 	 */
2401 	if (ret && !snp_page_reclaim(kvm, pfn) &&
2402 	    sev_populate_args->type == KVM_SEV_SNP_PAGE_TYPE_CPUID &&
2403 	    sev_populate_args->fw_error == SEV_RET_INVALID_PARAM) {
2404 		void *src_vaddr = kmap_local_page(src_page);
2405 		void *dst_vaddr = kmap_local_pfn(pfn);
2406 
2407 		memcpy(src_vaddr, dst_vaddr, PAGE_SIZE);
2408 		set_page_dirty(src_page);
2409 
2410 		kunmap_local(dst_vaddr);
2411 		kunmap_local(src_vaddr);
2412 	}
2413 
2414 out:
2415 	if (ret)
2416 		pr_debug("%s: error updating GFN %llx, return code %d (fw_error %d)\n",
2417 			 __func__, gfn, ret, sev_populate_args->fw_error);
2418 	return ret;
2419 }
2420 
2421 static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
2422 {
2423 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2424 	struct sev_gmem_populate_args sev_populate_args = {0};
2425 	struct kvm_sev_snp_launch_update params;
2426 	struct kvm_memory_slot *memslot;
2427 	long npages, count;
2428 	void __user *src;
2429 
2430 	if (!sev_snp_guest(kvm) || !sev->snp_context)
2431 		return -EINVAL;
2432 
2433 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
2434 		return -EFAULT;
2435 
2436 	pr_debug("%s: GFN start 0x%llx length 0x%llx type %d flags %d\n", __func__,
2437 		 params.gfn_start, params.len, params.type, params.flags);
2438 
2439 	if (!params.len || !PAGE_ALIGNED(params.len) || params.flags ||
2440 	    (params.type != KVM_SEV_SNP_PAGE_TYPE_NORMAL &&
2441 	     params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO &&
2442 	     params.type != KVM_SEV_SNP_PAGE_TYPE_UNMEASURED &&
2443 	     params.type != KVM_SEV_SNP_PAGE_TYPE_SECRETS &&
2444 	     params.type != KVM_SEV_SNP_PAGE_TYPE_CPUID))
2445 		return -EINVAL;
2446 
2447 	if (params.type == KVM_SEV_SNP_PAGE_TYPE_ZERO)
2448 		src = NULL;
2449 	else if (!params.uaddr || !PAGE_ALIGNED(params.uaddr))
2450 		return -EINVAL;
2451 	else
2452 		src = u64_to_user_ptr(params.uaddr);
2453 
2454 	npages = params.len / PAGE_SIZE;
2455 
2456 	/*
2457 	 * For each GFN that's being prepared as part of the initial guest
2458 	 * state, the following pre-conditions are verified:
2459 	 *
2460 	 *   1) The backing memslot is a valid private memslot.
2461 	 *   2) The GFN has been set to private via KVM_SET_MEMORY_ATTRIBUTES
2462 	 *      beforehand.
2463 	 *   3) The PFN of the guest_memfd has not already been set to private
2464 	 *      in the RMP table.
2465 	 *
2466 	 * The KVM MMU relies on kvm->mmu_invalidate_seq to retry nested page
2467 	 * faults if there's a race between a fault and an attribute update via
2468 	 * KVM_SET_MEMORY_ATTRIBUTES, and a similar approach could be utilized
2469 	 * here. However, kvm->slots_lock guards against both this as well as
2470 	 * concurrent memslot updates occurring while these checks are being
2471 	 * performed, so use that here to make it easier to reason about the
2472 	 * initial expected state and better guard against unexpected
2473 	 * situations.
2474 	 */
2475 	guard(mutex)(&kvm->slots_lock);
2476 
2477 	memslot = gfn_to_memslot(kvm, params.gfn_start);
2478 	if (!kvm_slot_has_gmem(memslot))
2479 		return -EINVAL;
2480 
2481 	sev_populate_args.sev_fd = argp->sev_fd;
2482 	sev_populate_args.type = params.type;
2483 
2484 	count = kvm_gmem_populate(kvm, params.gfn_start, src, npages,
2485 				  params.type == KVM_SEV_SNP_PAGE_TYPE_CPUID,
2486 				  sev_gmem_post_populate, &sev_populate_args);
2487 	if (count < 0) {
2488 		argp->error = sev_populate_args.fw_error;
2489 		pr_debug("%s: kvm_gmem_populate failed, ret %ld (fw_error %d)\n",
2490 			 __func__, count, argp->error);
2491 		return -EIO;
2492 	}
2493 
2494 	params.gfn_start += count;
2495 	params.len -= count * PAGE_SIZE;
2496 	if (params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO)
2497 		params.uaddr += count * PAGE_SIZE;
2498 
2499 	if (copy_to_user(u64_to_user_ptr(argp->data), &params, sizeof(params)))
2500 		return -EFAULT;
2501 
2502 	return 0;
2503 }
2504 
2505 static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
2506 {
2507 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2508 	struct sev_data_snp_launch_update data = {};
2509 	struct kvm_vcpu *vcpu;
2510 	unsigned long i;
2511 	int ret;
2512 
2513 	if (kvm_is_vcpu_creation_in_progress(kvm))
2514 		return -EBUSY;
2515 
2516 	ret = kvm_lock_all_vcpus(kvm);
2517 	if (ret)
2518 		return ret;
2519 
2520 	data.gctx_paddr = __psp_pa(sev->snp_context);
2521 	data.page_type = SNP_PAGE_TYPE_VMSA;
2522 
2523 	kvm_for_each_vcpu(i, vcpu, kvm) {
2524 		struct vcpu_svm *svm = to_svm(vcpu);
2525 		u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
2526 
2527 		ret = sev_es_sync_vmsa(svm);
2528 		if (ret)
2529 			goto out;
2530 
2531 		/* Transition the VMSA page to a firmware state. */
2532 		ret = rmp_make_private(pfn, INITIAL_VMSA_GPA, PG_LEVEL_4K, sev->asid, true);
2533 		if (ret)
2534 			goto out;
2535 
2536 		/* Issue the SNP command to encrypt the VMSA */
2537 		data.address = __sme_pa(svm->sev_es.vmsa);
2538 		ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
2539 				      &data, &argp->error);
2540 		if (ret) {
2541 			snp_page_reclaim(kvm, pfn);
2542 
2543 			goto out;
2544 		}
2545 
2546 		svm->vcpu.arch.guest_state_protected = true;
2547 		/*
2548 		 * SEV-ES (and thus SNP) guest mandates LBR Virtualization to
2549 		 * be _always_ ON. Enable it only after setting
2550 		 * guest_state_protected because KVM_SET_MSRS allows dynamic
2551 		 * toggling of LBRV (for performance reason) on write access to
2552 		 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set.
2553 		 */
2554 		svm_enable_lbrv(vcpu);
2555 	}
2556 
2557 out:
2558 	kvm_unlock_all_vcpus(kvm);
2559 	return ret;
2560 }
2561 
2562 static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
2563 {
2564 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2565 	struct kvm_sev_snp_launch_finish params;
2566 	struct sev_data_snp_launch_finish *data;
2567 	void *id_block = NULL, *id_auth = NULL;
2568 	int ret;
2569 
2570 	if (!sev_snp_guest(kvm))
2571 		return -ENOTTY;
2572 
2573 	if (!sev->snp_context)
2574 		return -EINVAL;
2575 
2576 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
2577 		return -EFAULT;
2578 
2579 	if (params.flags)
2580 		return -EINVAL;
2581 
2582 	/* Measure all vCPUs using LAUNCH_UPDATE before finalizing the launch flow. */
2583 	ret = snp_launch_update_vmsa(kvm, argp);
2584 	if (ret)
2585 		return ret;
2586 
2587 	data = kzalloc_obj(*data, GFP_KERNEL_ACCOUNT);
2588 	if (!data)
2589 		return -ENOMEM;
2590 
2591 	if (params.id_block_en) {
2592 		id_block = psp_copy_user_blob(params.id_block_uaddr, KVM_SEV_SNP_ID_BLOCK_SIZE);
2593 		if (IS_ERR(id_block)) {
2594 			ret = PTR_ERR(id_block);
2595 			goto e_free;
2596 		}
2597 
2598 		data->id_block_en = 1;
2599 		data->id_block_paddr = __sme_pa(id_block);
2600 
2601 		id_auth = psp_copy_user_blob(params.id_auth_uaddr, KVM_SEV_SNP_ID_AUTH_SIZE);
2602 		if (IS_ERR(id_auth)) {
2603 			ret = PTR_ERR(id_auth);
2604 			goto e_free_id_block;
2605 		}
2606 
2607 		data->id_auth_paddr = __sme_pa(id_auth);
2608 
2609 		if (params.auth_key_en)
2610 			data->auth_key_en = 1;
2611 	}
2612 
2613 	data->vcek_disabled = params.vcek_disabled;
2614 
2615 	memcpy(data->host_data, params.host_data, KVM_SEV_SNP_FINISH_DATA_SIZE);
2616 	data->gctx_paddr = __psp_pa(sev->snp_context);
2617 	ret = sev_issue_cmd(kvm, SEV_CMD_SNP_LAUNCH_FINISH, data, &argp->error);
2618 
2619 	/*
2620 	 * Now that there will be no more SNP_LAUNCH_UPDATE ioctls, private pages
2621 	 * can be given to the guest simply by marking the RMP entry as private.
2622 	 * This can happen on first access and also with KVM_PRE_FAULT_MEMORY.
2623 	 */
2624 	if (!ret)
2625 		kvm->arch.pre_fault_allowed = true;
2626 
2627 	kfree(id_auth);
2628 
2629 e_free_id_block:
2630 	kfree(id_block);
2631 
2632 e_free:
2633 	kfree(data);
2634 
2635 	return ret;
2636 }
2637 
2638 static int snp_enable_certs(struct kvm *kvm)
2639 {
2640 	if (kvm->created_vcpus || !sev_snp_guest(kvm))
2641 		return -EINVAL;
2642 
2643 	to_kvm_sev_info(kvm)->snp_certs_enabled = true;
2644 
2645 	return 0;
2646 }
2647 
2648 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
2649 {
2650 	struct kvm_sev_cmd sev_cmd;
2651 	int r;
2652 
2653 	if (!sev_enabled)
2654 		return -ENOTTY;
2655 
2656 	if (!argp)
2657 		return 0;
2658 
2659 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
2660 		return -EFAULT;
2661 
2662 	guard(mutex)(&kvm->lock);
2663 
2664 	/* Only the enc_context_owner handles some memory enc operations. */
2665 	if (is_mirroring_enc_context(kvm) &&
2666 	    !is_cmd_allowed_from_mirror(sev_cmd.id))
2667 		return -EINVAL;
2668 
2669 	/*
2670 	 * Once KVM_SEV_INIT2 initializes a KVM instance as an SNP guest, only
2671 	 * allow the use of SNP-specific commands.
2672 	 */
2673 	if (sev_snp_guest(kvm) && sev_cmd.id < KVM_SEV_SNP_LAUNCH_START)
2674 		return -EPERM;
2675 
2676 	switch (sev_cmd.id) {
2677 	case KVM_SEV_ES_INIT:
2678 		if (!sev_es_enabled)
2679 			return -ENOTTY;
2680 		fallthrough;
2681 	case KVM_SEV_INIT:
2682 		r = sev_guest_init(kvm, &sev_cmd);
2683 		break;
2684 	case KVM_SEV_INIT2:
2685 		r = sev_guest_init2(kvm, &sev_cmd);
2686 		break;
2687 	case KVM_SEV_LAUNCH_START:
2688 		r = sev_launch_start(kvm, &sev_cmd);
2689 		break;
2690 	case KVM_SEV_LAUNCH_UPDATE_DATA:
2691 		r = sev_launch_update_data(kvm, &sev_cmd);
2692 		break;
2693 	case KVM_SEV_LAUNCH_UPDATE_VMSA:
2694 		r = sev_launch_update_vmsa(kvm, &sev_cmd);
2695 		break;
2696 	case KVM_SEV_LAUNCH_MEASURE:
2697 		r = sev_launch_measure(kvm, &sev_cmd);
2698 		break;
2699 	case KVM_SEV_LAUNCH_FINISH:
2700 		r = sev_launch_finish(kvm, &sev_cmd);
2701 		break;
2702 	case KVM_SEV_GUEST_STATUS:
2703 		r = sev_guest_status(kvm, &sev_cmd);
2704 		break;
2705 	case KVM_SEV_DBG_DECRYPT:
2706 	case KVM_SEV_DBG_ENCRYPT:
2707 		r = sev_dbg_crypt(kvm, &sev_cmd, sev_cmd.id);
2708 		break;
2709 	case KVM_SEV_LAUNCH_SECRET:
2710 		r = sev_launch_secret(kvm, &sev_cmd);
2711 		break;
2712 	case KVM_SEV_GET_ATTESTATION_REPORT:
2713 		r = sev_get_attestation_report(kvm, &sev_cmd);
2714 		break;
2715 	case KVM_SEV_SEND_START:
2716 		r = sev_send_start(kvm, &sev_cmd);
2717 		break;
2718 	case KVM_SEV_SEND_UPDATE_DATA:
2719 		r = sev_send_update_data(kvm, &sev_cmd);
2720 		break;
2721 	case KVM_SEV_SEND_FINISH:
2722 		r = sev_send_finish(kvm, &sev_cmd);
2723 		break;
2724 	case KVM_SEV_SEND_CANCEL:
2725 		r = sev_send_cancel(kvm, &sev_cmd);
2726 		break;
2727 	case KVM_SEV_RECEIVE_START:
2728 		r = sev_receive_start(kvm, &sev_cmd);
2729 		break;
2730 	case KVM_SEV_RECEIVE_UPDATE_DATA:
2731 		r = sev_receive_update_data(kvm, &sev_cmd);
2732 		break;
2733 	case KVM_SEV_RECEIVE_FINISH:
2734 		r = sev_receive_finish(kvm, &sev_cmd);
2735 		break;
2736 	case KVM_SEV_SNP_LAUNCH_START:
2737 		r = snp_launch_start(kvm, &sev_cmd);
2738 		break;
2739 	case KVM_SEV_SNP_LAUNCH_UPDATE:
2740 		r = snp_launch_update(kvm, &sev_cmd);
2741 		break;
2742 	case KVM_SEV_SNP_LAUNCH_FINISH:
2743 		r = snp_launch_finish(kvm, &sev_cmd);
2744 		break;
2745 	case KVM_SEV_SNP_ENABLE_REQ_CERTS:
2746 		r = snp_enable_certs(kvm);
2747 		break;
2748 	default:
2749 		return -EINVAL;
2750 	}
2751 
2752 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
2753 		r = -EFAULT;
2754 
2755 	return r;
2756 }
2757 
2758 int sev_mem_enc_register_region(struct kvm *kvm,
2759 				struct kvm_enc_region *range)
2760 {
2761 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2762 	struct enc_region *region;
2763 	int ret = 0;
2764 
2765 	guard(mutex)(&kvm->lock);
2766 
2767 	if (!sev_guest(kvm))
2768 		return -ENOTTY;
2769 
2770 	/* If kvm is mirroring encryption context it isn't responsible for it */
2771 	if (is_mirroring_enc_context(kvm))
2772 		return -EINVAL;
2773 
2774 	region = kzalloc_obj(*region, GFP_KERNEL_ACCOUNT);
2775 	if (!region)
2776 		return -ENOMEM;
2777 
2778 	/*
2779 	 * Do NOT specify FOLL_WRITE, as KVM isn't using the pinned pages to
2780 	 * write memory, and FOLL_LONGTERM itself triggers CoW unshare.
2781 	 */
2782 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages,
2783 				       FOLL_LONGTERM);
2784 	if (IS_ERR(region->pages)) {
2785 		ret = PTR_ERR(region->pages);
2786 		goto e_free;
2787 	}
2788 
2789 	/*
2790 	 * The guest may change the memory encryption attribute from C=0 -> C=1
2791 	 * or vice versa for this memory range. Lets make sure caches are
2792 	 * flushed to ensure that guest data gets written into memory with
2793 	 * correct C-bit.  Note, this must be done before dropping kvm->lock,
2794 	 * as region and its array of pages can be freed by a different task
2795 	 * once kvm->lock is released.
2796 	 */
2797 	sev_clflush_pages(region->pages, region->npages);
2798 
2799 	region->uaddr = range->addr;
2800 	region->size = range->size;
2801 
2802 	list_add_tail(&region->list, &sev->regions_list);
2803 	return ret;
2804 
2805 e_free:
2806 	kfree(region);
2807 	return ret;
2808 }
2809 
2810 static struct enc_region *
2811 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
2812 {
2813 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2814 	struct list_head *head = &sev->regions_list;
2815 	struct enc_region *i;
2816 
2817 	list_for_each_entry(i, head, list) {
2818 		if (i->uaddr == range->addr &&
2819 		    i->size == range->size)
2820 			return i;
2821 	}
2822 
2823 	return NULL;
2824 }
2825 
2826 static void __unregister_enc_region_locked(struct kvm *kvm,
2827 					   struct enc_region *region)
2828 {
2829 	sev_unpin_memory(kvm, region->pages, region->npages);
2830 	list_del(&region->list);
2831 	kfree(region);
2832 }
2833 
2834 int sev_mem_enc_unregister_region(struct kvm *kvm,
2835 				  struct kvm_enc_region *range)
2836 {
2837 	struct enc_region *region;
2838 
2839 	/* If kvm is mirroring encryption context it isn't responsible for it */
2840 	if (is_mirroring_enc_context(kvm))
2841 		return -EINVAL;
2842 
2843 	guard(mutex)(&kvm->lock);
2844 
2845 	if (!sev_guest(kvm))
2846 		return -ENOTTY;
2847 
2848 	region = find_enc_region(kvm, range);
2849 	if (!region)
2850 		return -EINVAL;
2851 
2852 	sev_writeback_caches(kvm);
2853 
2854 	__unregister_enc_region_locked(kvm, region);
2855 
2856 	return 0;
2857 }
2858 
2859 int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2860 {
2861 	CLASS(fd, f)(source_fd);
2862 	struct kvm *source_kvm;
2863 	struct kvm_sev_info *source_sev, *mirror_sev;
2864 	int ret;
2865 
2866 	if (fd_empty(f))
2867 		return -EBADF;
2868 
2869 	if (!file_is_kvm(fd_file(f)))
2870 		return -EBADF;
2871 
2872 	source_kvm = fd_file(f)->private_data;
2873 	ret = sev_lock_two_vms(kvm, source_kvm);
2874 	if (ret)
2875 		return ret;
2876 
2877 	/*
2878 	 * Mirrors of mirrors should work, but let's not get silly.  Also
2879 	 * disallow out-of-band SEV/SEV-ES init if the target is already an
2880 	 * SEV guest, or if vCPUs have been created.  KVM relies on vCPUs being
2881 	 * created after SEV/SEV-ES initialization, e.g. to init intercepts.
2882 	 * Also do not allow SNP VM mirroring until additional state transfer is implemented.
2883 	 */
2884 	if (sev_guest(kvm) || !sev_guest(source_kvm) || sev_snp_guest(source_kvm) ||
2885 	    is_mirroring_enc_context(source_kvm) || kvm->created_vcpus) {
2886 		ret = -EINVAL;
2887 		goto e_unlock;
2888 	}
2889 
2890 	mirror_sev = to_kvm_sev_info(kvm);
2891 	if (!zalloc_cpumask_var(&mirror_sev->have_run_cpus, GFP_KERNEL_ACCOUNT)) {
2892 		ret = -ENOMEM;
2893 		goto e_unlock;
2894 	}
2895 
2896 	/*
2897 	 * The mirror kvm holds an enc_context_owner ref so its asid can't
2898 	 * disappear until we're done with it
2899 	 */
2900 	source_sev = to_kvm_sev_info(source_kvm);
2901 
2902 	/* Set enc_context_owner and copy its encryption context over */
2903 	mutex_lock(&sev_mirror_lock);
2904 	kvm_get_kvm(source_kvm);
2905 	list_add_tail(&mirror_sev->mirror_entry, &source_sev->mirror_vms);
2906 	mirror_sev->enc_context_owner = source_kvm;
2907 	mutex_unlock(&sev_mirror_lock);
2908 
2909 	mirror_sev->active = true;
2910 	mirror_sev->asid = source_sev->asid;
2911 	mirror_sev->fd = source_sev->fd;
2912 	mirror_sev->es_active = source_sev->es_active;
2913 	mirror_sev->need_init = false;
2914 	mirror_sev->handle = source_sev->handle;
2915 	INIT_LIST_HEAD(&mirror_sev->regions_list);
2916 	INIT_LIST_HEAD(&mirror_sev->mirror_vms);
2917 	ret = 0;
2918 
2919 	/*
2920 	 * Do not copy ap_jump_table. Since the mirror does not share the same
2921 	 * KVM contexts as the original, and they may have different
2922 	 * memory-views.
2923 	 */
2924 
2925 e_unlock:
2926 	sev_unlock_two_vms(kvm, source_kvm);
2927 	return ret;
2928 }
2929 
2930 static int snp_decommission_context(struct kvm *kvm)
2931 {
2932 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2933 	struct sev_data_snp_addr data = {};
2934 	int ret;
2935 
2936 	/* If context is not created then do nothing */
2937 	if (!sev->snp_context)
2938 		return 0;
2939 
2940 	/* Do the decommision, which will unbind the ASID from the SNP context */
2941 	data.address = __sme_pa(sev->snp_context);
2942 	down_write(&sev_deactivate_lock);
2943 	ret = sev_do_cmd(SEV_CMD_SNP_DECOMMISSION, &data, NULL);
2944 	up_write(&sev_deactivate_lock);
2945 
2946 	if (WARN_ONCE(ret, "Failed to release guest context, ret %d", ret))
2947 		return ret;
2948 
2949 	snp_free_firmware_page(sev->snp_context);
2950 	sev->snp_context = NULL;
2951 
2952 	return 0;
2953 }
2954 
2955 void sev_vm_init(struct kvm *kvm)
2956 {
2957 	switch (kvm->arch.vm_type) {
2958 	case KVM_X86_DEFAULT_VM:
2959 	case KVM_X86_SW_PROTECTED_VM:
2960 		break;
2961 	case KVM_X86_SNP_VM:
2962 		kvm->arch.has_private_mem = true;
2963 		fallthrough;
2964 	case KVM_X86_SEV_ES_VM:
2965 		kvm->arch.has_protected_state = true;
2966 		fallthrough;
2967 	case KVM_X86_SEV_VM:
2968 		kvm->arch.pre_fault_allowed = !kvm->arch.has_private_mem;
2969 		to_kvm_sev_info(kvm)->need_init = true;
2970 		break;
2971 	default:
2972 		WARN_ONCE(1, "Unsupported VM type %u", kvm->arch.vm_type);
2973 		break;
2974 	}
2975 }
2976 
2977 void sev_vm_destroy(struct kvm *kvm)
2978 {
2979 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2980 	struct list_head *head = &sev->regions_list;
2981 	struct list_head *pos, *q;
2982 
2983 	if (!sev_guest(kvm))
2984 		return;
2985 
2986 	WARN_ON(!list_empty(&sev->mirror_vms));
2987 
2988 	free_cpumask_var(sev->have_run_cpus);
2989 
2990 	/*
2991 	 * If this is a mirror VM, remove it from the owner's list of a mirrors
2992 	 * and skip ASID cleanup (the ASID is tied to the lifetime of the owner).
2993 	 * Note, mirror VMs don't support registering encrypted regions.
2994 	 */
2995 	if (is_mirroring_enc_context(kvm)) {
2996 		struct kvm *owner_kvm;
2997 
2998 		mutex_lock(&sev_mirror_lock);
2999 		owner_kvm = sev->enc_context_owner;
3000 		list_del(&sev->mirror_entry);
3001 		sev->enc_context_owner = NULL;
3002 
3003 		/*
3004 		 * The reference to owner_kvm cannot move after sev_mirror_lock is
3005 		 * released.  Release it before kvm_put_kvm() so that owner_kvm is
3006 		 * never destroyed inside sev_mirror_lock.
3007 		 */
3008 		mutex_unlock(&sev_mirror_lock);
3009 		kvm_put_kvm(owner_kvm);
3010 		return;
3011 	}
3012 
3013 
3014 	/*
3015 	 * if userspace was terminated before unregistering the memory regions
3016 	 * then lets unpin all the registered memory.
3017 	 */
3018 	if (!list_empty(head)) {
3019 		list_for_each_safe(pos, q, head) {
3020 			__unregister_enc_region_locked(kvm,
3021 				list_entry(pos, struct enc_region, list));
3022 			cond_resched();
3023 		}
3024 	}
3025 
3026 	if (sev_snp_guest(kvm)) {
3027 		snp_guest_req_cleanup(kvm);
3028 
3029 		/*
3030 		 * Decomission handles unbinding of the ASID. If it fails for
3031 		 * some unexpected reason, just leak the ASID.
3032 		 */
3033 		if (snp_decommission_context(kvm))
3034 			return;
3035 	} else {
3036 		sev_unbind_asid(kvm, sev->handle);
3037 	}
3038 
3039 	sev_asid_free(sev);
3040 }
3041 
3042 void __init sev_set_cpu_caps(void)
3043 {
3044 	if (sev_enabled)
3045 		kvm_cpu_cap_set(X86_FEATURE_SEV);
3046 
3047 	if (sev_es_enabled)
3048 		kvm_cpu_cap_set(X86_FEATURE_SEV_ES);
3049 
3050 	if (sev_snp_enabled)
3051 		kvm_cpu_cap_set(X86_FEATURE_SEV_SNP);
3052 }
3053 
3054 static bool is_sev_snp_initialized(void)
3055 {
3056 	struct sev_user_data_snp_status *status;
3057 	struct sev_data_snp_addr buf;
3058 	bool initialized = false;
3059 	int ret, error = 0;
3060 
3061 	status = snp_alloc_firmware_page(GFP_KERNEL | __GFP_ZERO);
3062 	if (!status)
3063 		return false;
3064 
3065 	buf.address = __psp_pa(status);
3066 	ret = sev_do_cmd(SEV_CMD_SNP_PLATFORM_STATUS, &buf, &error);
3067 	if (ret) {
3068 		pr_err("SEV: SNP_PLATFORM_STATUS failed ret=%d, fw_error=%d (%#x)\n",
3069 		       ret, error, error);
3070 		goto out;
3071 	}
3072 
3073 	initialized = !!status->state;
3074 
3075 out:
3076 	snp_free_firmware_page(status);
3077 
3078 	return initialized;
3079 }
3080 
3081 static const char * __init sev_str_feature_state(bool is_supported, bool is_usable)
3082 {
3083 	return is_supported ? is_usable ? "enabled" : "unusable" : "disabled";
3084 }
3085 
3086 void __init sev_hardware_setup(void)
3087 {
3088 	unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count;
3089 	struct sev_platform_init_args init_args = {0};
3090 	bool sev_snp_supported = false;
3091 	bool sev_es_supported = false;
3092 	bool sev_supported = false;
3093 	u32 vm_types = 0;
3094 
3095 	if (!sev_enabled || !npt_enabled || !nrips)
3096 		goto out;
3097 
3098 	/*
3099 	 * SEV must obviously be supported in hardware.  Sanity check that the
3100 	 * CPU supports decode assists, which is mandatory for SEV guests to
3101 	 * support instruction emulation.  Ditto for flushing by ASID, as SEV
3102 	 * guests are bound to a single ASID, i.e. KVM can't rotate to a new
3103 	 * ASID to effect a TLB flush.
3104 	 */
3105 	if (!boot_cpu_has(X86_FEATURE_SEV) ||
3106 	    WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_DECODEASSISTS)) ||
3107 	    WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_FLUSHBYASID)))
3108 		goto out;
3109 
3110 	/*
3111 	 * The kernel's initcall infrastructure lacks the ability to express
3112 	 * dependencies between initcalls, whereas the modules infrastructure
3113 	 * automatically handles dependencies via symbol loading.  Ensure the
3114 	 * PSP SEV driver is initialized before proceeding if KVM is built-in,
3115 	 * as the dependency isn't handled by the initcall infrastructure.
3116 	 */
3117 	if (IS_BUILTIN(CONFIG_KVM_AMD) && sev_module_init())
3118 		goto out;
3119 
3120 	/* Retrieve SEV CPUID information */
3121 	cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
3122 
3123 	/* Set encryption bit location for SEV-ES guests */
3124 	sev_enc_bit = ebx & 0x3f;
3125 
3126 	/* Maximum number of encrypted guests supported simultaneously */
3127 	max_sev_asid = ecx;
3128 	if (!max_sev_asid)
3129 		goto out;
3130 
3131 	/* Minimum ASID value that should be used for SEV guest */
3132 	min_sev_asid = edx;
3133 	sev_me_mask = 1UL << (ebx & 0x3f);
3134 
3135 	/*
3136 	 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap,
3137 	 * even though it's never used, so that the bitmap is indexed by the
3138 	 * actual ASID.
3139 	 */
3140 	nr_asids = max_sev_asid + 1;
3141 	sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
3142 	if (!sev_asid_bitmap)
3143 		goto out;
3144 
3145 	sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
3146 	if (!sev_reclaim_asid_bitmap) {
3147 		bitmap_free(sev_asid_bitmap);
3148 		sev_asid_bitmap = NULL;
3149 		goto out;
3150 	}
3151 
3152 	if (min_sev_asid <= max_sev_asid) {
3153 		sev_asid_count = max_sev_asid - min_sev_asid + 1;
3154 		WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count));
3155 	}
3156 	sev_supported = true;
3157 
3158 	/* SEV-ES support requested? */
3159 	if (!sev_es_enabled)
3160 		goto out;
3161 
3162 	/*
3163 	 * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
3164 	 * instruction stream, i.e. can't emulate in response to a #NPF and
3165 	 * instead relies on #NPF(RSVD) being reflected into the guest as #VC
3166 	 * (the guest can then do a #VMGEXIT to request MMIO emulation).
3167 	 */
3168 	if (!enable_mmio_caching)
3169 		goto out;
3170 
3171 	/* Does the CPU support SEV-ES? */
3172 	if (!boot_cpu_has(X86_FEATURE_SEV_ES))
3173 		goto out;
3174 
3175 	if (!lbrv) {
3176 		WARN_ONCE(!boot_cpu_has(X86_FEATURE_LBRV),
3177 			  "LBRV must be present for SEV-ES support");
3178 		goto out;
3179 	}
3180 
3181 	/* Has the system been allocated ASIDs for SEV-ES? */
3182 	if (min_sev_asid == 1)
3183 		goto out;
3184 
3185 	min_sev_es_asid = min_snp_asid = 1;
3186 	max_sev_es_asid = max_snp_asid = min_sev_asid - 1;
3187 
3188 	sev_es_asid_count = min_sev_asid - 1;
3189 	WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count));
3190 	sev_es_supported = true;
3191 	sev_snp_supported = sev_snp_enabled && cc_platform_has(CC_ATTR_HOST_SEV_SNP);
3192 
3193 out:
3194 	if (sev_enabled) {
3195 		init_args.probe = true;
3196 
3197 		if (sev_is_snp_ciphertext_hiding_supported())
3198 			init_args.max_snp_asid = min(nr_ciphertext_hiding_asids,
3199 						     min_sev_asid - 1);
3200 
3201 		if (sev_platform_init(&init_args))
3202 			sev_supported = sev_es_supported = sev_snp_supported = false;
3203 		else if (sev_snp_supported)
3204 			sev_snp_supported = is_sev_snp_initialized();
3205 
3206 		if (sev_snp_supported) {
3207 			snp_supported_policy_bits = sev_get_snp_policy_bits() &
3208 						    KVM_SNP_POLICY_MASK_VALID;
3209 			nr_ciphertext_hiding_asids = init_args.max_snp_asid;
3210 		}
3211 
3212 		/*
3213 		 * If ciphertext hiding is enabled, the joint SEV-ES/SEV-SNP
3214 		 * ASID range is partitioned into separate SEV-ES and SEV-SNP
3215 		 * ASID ranges, with the SEV-SNP range being [1..max_snp_asid]
3216 		 * and the SEV-ES range being (max_snp_asid..max_sev_es_asid].
3217 		 * Note, SEV-ES may effectively be disabled if all ASIDs from
3218 		 * the joint range are assigned to SEV-SNP.
3219 		 */
3220 		if (nr_ciphertext_hiding_asids) {
3221 			max_snp_asid = nr_ciphertext_hiding_asids;
3222 			min_sev_es_asid = max_snp_asid + 1;
3223 			pr_info("SEV-SNP ciphertext hiding enabled\n");
3224 		}
3225 	}
3226 
3227 	if (sev_supported && min_sev_asid <= max_sev_asid)
3228 		vm_types |= BIT(KVM_X86_SEV_VM);
3229 	if (sev_es_supported && min_sev_es_asid <= max_sev_es_asid)
3230 		vm_types |= BIT(KVM_X86_SEV_ES_VM);
3231 	if (sev_snp_supported)
3232 		vm_types |= BIT(KVM_X86_SNP_VM);
3233 	vm_types &= sev_firmware_supported_vm_types();
3234 
3235 	kvm_caps.supported_vm_types |= vm_types;
3236 
3237 	if (boot_cpu_has(X86_FEATURE_SEV))
3238 		pr_info("SEV %s (ASIDs %u - %u)\n",
3239 			sev_str_feature_state(sev_supported, vm_types & BIT(KVM_X86_SEV_VM)),
3240 			min_sev_asid, max_sev_asid);
3241 	if (boot_cpu_has(X86_FEATURE_SEV_ES))
3242 		pr_info("SEV-ES %s (ASIDs %u - %u)\n",
3243 			sev_str_feature_state(sev_es_supported, vm_types & BIT(KVM_X86_SEV_ES_VM)),
3244 			min_sev_es_asid, max_sev_es_asid);
3245 	if (boot_cpu_has(X86_FEATURE_SEV_SNP))
3246 		pr_info("SEV-SNP %s (ASIDs %u - %u)\n",
3247 			sev_str_feature_state(sev_snp_supported, vm_types & BIT(KVM_X86_SNP_VM)),
3248 			min_snp_asid, max_snp_asid);
3249 
3250 	sev_enabled = sev_supported;
3251 	sev_es_enabled = sev_es_supported;
3252 	sev_snp_enabled = sev_snp_supported;
3253 
3254 	sev_supported_vmsa_features = 0;
3255 
3256 	if (sev_es_enabled && cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) &&
3257 	    cpu_feature_enabled(X86_FEATURE_NO_NESTED_DATA_BP))
3258 		sev_supported_vmsa_features |= SVM_SEV_FEAT_DEBUG_SWAP;
3259 
3260 	if (sev_snp_enabled && tsc_khz && cpu_feature_enabled(X86_FEATURE_SNP_SECURE_TSC))
3261 		sev_supported_vmsa_features |= SVM_SEV_FEAT_SECURE_TSC;
3262 }
3263 
3264 void sev_hardware_unsetup(void)
3265 {
3266 	if (!sev_enabled)
3267 		return;
3268 
3269 	/* No need to take sev_bitmap_lock, all VMs have been destroyed. */
3270 	sev_flush_asids(1, max_sev_asid);
3271 
3272 	bitmap_free(sev_asid_bitmap);
3273 	bitmap_free(sev_reclaim_asid_bitmap);
3274 
3275 	misc_cg_set_capacity(MISC_CG_RES_SEV, 0);
3276 	misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0);
3277 
3278 	sev_platform_shutdown();
3279 }
3280 
3281 int sev_cpu_init(struct svm_cpu_data *sd)
3282 {
3283 	if (!sev_enabled)
3284 		return 0;
3285 
3286 	sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL);
3287 	if (!sd->sev_vmcbs)
3288 		return -ENOMEM;
3289 
3290 	return 0;
3291 }
3292 
3293 /*
3294  * Pages used by hardware to hold guest encrypted state must be flushed before
3295  * returning them to the system.
3296  */
3297 static void sev_flush_encrypted_page(struct kvm_vcpu *vcpu, void *va)
3298 {
3299 	unsigned int asid = sev_get_asid(vcpu->kvm);
3300 
3301 	/*
3302 	 * Note!  The address must be a kernel address, as regular page walk
3303 	 * checks are performed by VM_PAGE_FLUSH, i.e. operating on a user
3304 	 * address is non-deterministic and unsafe.  This function deliberately
3305 	 * takes a pointer to deter passing in a user address.
3306 	 */
3307 	unsigned long addr = (unsigned long)va;
3308 
3309 	/*
3310 	 * If CPU enforced cache coherency for encrypted mappings of the
3311 	 * same physical page is supported, use CLFLUSHOPT instead. NOTE: cache
3312 	 * flush is still needed in order to work properly with DMA devices.
3313 	 */
3314 	if (boot_cpu_has(X86_FEATURE_SME_COHERENT)) {
3315 		clflush_cache_range(va, PAGE_SIZE);
3316 		return;
3317 	}
3318 
3319 	/*
3320 	 * VM Page Flush takes a host virtual address and a guest ASID.  Fall
3321 	 * back to full writeback of caches if this faults so as not to make
3322 	 * any problems worse by leaving stale encrypted data in the cache.
3323 	 */
3324 	if (WARN_ON_ONCE(wrmsrq_safe(MSR_AMD64_VM_PAGE_FLUSH, addr | asid)))
3325 		goto do_sev_writeback_caches;
3326 
3327 	return;
3328 
3329 do_sev_writeback_caches:
3330 	sev_writeback_caches(vcpu->kvm);
3331 }
3332 
3333 void sev_guest_memory_reclaimed(struct kvm *kvm)
3334 {
3335 	/*
3336 	 * With SNP+gmem, private/encrypted memory is unreachable via the
3337 	 * hva-based mmu notifiers, i.e. these events are explicitly scoped to
3338 	 * shared pages, where there's no need to flush caches.
3339 	 *
3340 	 * Checking for SEV+ outside of kvm->lock is safe as __sev_guest_init()
3341 	 * can only be done before vCPUs are created, caches can be incoherent
3342 	 * if and only if a vCPU was run, and either this task will see the VM
3343 	 * as being SEV+ or the vCPU won't be to access the memory (because of
3344 	 * the in-progress invalidation).
3345 	 */
3346 	if (!____sev_guest(kvm) || ____sev_snp_guest(kvm))
3347 		return;
3348 
3349 	sev_writeback_caches(kvm);
3350 }
3351 
3352 static void dump_ghcb(struct vcpu_svm *svm)
3353 {
3354 	struct vmcb_control_area *control = &svm->vmcb->control;
3355 	unsigned int nbits;
3356 
3357 	/* Re-use the dump_invalid_vmcb module parameter */
3358 	if (!dump_invalid_vmcb) {
3359 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3360 		return;
3361 	}
3362 
3363 	nbits = sizeof(svm->sev_es.valid_bitmap) * 8;
3364 
3365 	/*
3366 	 * Print KVM's snapshot of the GHCB values that were (unsuccessfully)
3367 	 * used to handle the exit.  If the guest has since modified the GHCB
3368 	 * itself, dumping the raw GHCB won't help debug why KVM was unable to
3369 	 * handle the VMGEXIT that KVM observed.
3370 	 */
3371 	pr_err("GHCB (GPA=%016llx) snapshot:\n", svm->vmcb->control.ghcb_gpa);
3372 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
3373 	       control->exit_code, kvm_ghcb_sw_exit_code_is_valid(svm));
3374 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
3375 	       control->exit_info_1, kvm_ghcb_sw_exit_info_1_is_valid(svm));
3376 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
3377 	       control->exit_info_2, kvm_ghcb_sw_exit_info_2_is_valid(svm));
3378 	pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
3379 	       svm->sev_es.sw_scratch, kvm_ghcb_sw_scratch_is_valid(svm));
3380 	pr_err("%-20s%*pb\n", "valid_bitmap", nbits, svm->sev_es.valid_bitmap);
3381 }
3382 
3383 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
3384 {
3385 	struct kvm_vcpu *vcpu = &svm->vcpu;
3386 	struct ghcb *ghcb = svm->sev_es.ghcb;
3387 
3388 	/*
3389 	 * The GHCB protocol so far allows for the following data
3390 	 * to be returned:
3391 	 *   GPRs RAX, RBX, RCX, RDX
3392 	 *
3393 	 * Copy their values, even if they may not have been written during the
3394 	 * VM-Exit.  It's the guest's responsibility to not consume random data.
3395 	 */
3396 	ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
3397 	ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
3398 	ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
3399 	ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
3400 }
3401 
3402 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
3403 {
3404 	struct vmcb_control_area *control = &svm->vmcb->control;
3405 	struct kvm_vcpu *vcpu = &svm->vcpu;
3406 	struct ghcb *ghcb = svm->sev_es.ghcb;
3407 
3408 	/*
3409 	 * The GHCB protocol so far allows for the following data
3410 	 * to be supplied:
3411 	 *   GPRs RAX, RBX, RCX, RDX
3412 	 *   XCR0
3413 	 *   CPL
3414 	 *
3415 	 * VMMCALL allows the guest to provide extra registers. KVM also
3416 	 * expects RSI for hypercalls, so include that, too.
3417 	 *
3418 	 * Copy their values to the appropriate location if supplied.
3419 	 */
3420 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
3421 
3422 	BUILD_BUG_ON(sizeof(svm->sev_es.valid_bitmap) != sizeof(ghcb->save.valid_bitmap));
3423 	memcpy(&svm->sev_es.valid_bitmap, &ghcb->save.valid_bitmap, sizeof(ghcb->save.valid_bitmap));
3424 
3425 	vcpu->arch.regs[VCPU_REGS_RAX] = kvm_ghcb_get_rax_if_valid(svm);
3426 	vcpu->arch.regs[VCPU_REGS_RBX] = kvm_ghcb_get_rbx_if_valid(svm);
3427 	vcpu->arch.regs[VCPU_REGS_RCX] = kvm_ghcb_get_rcx_if_valid(svm);
3428 	vcpu->arch.regs[VCPU_REGS_RDX] = kvm_ghcb_get_rdx_if_valid(svm);
3429 	vcpu->arch.regs[VCPU_REGS_RSI] = kvm_ghcb_get_rsi_if_valid(svm);
3430 
3431 	svm->vmcb->save.cpl = kvm_ghcb_get_cpl_if_valid(svm);
3432 
3433 	if (kvm_ghcb_xcr0_is_valid(svm))
3434 		__kvm_set_xcr(vcpu, 0, kvm_ghcb_get_xcr0(svm));
3435 
3436 	if (kvm_ghcb_xss_is_valid(svm))
3437 		__kvm_emulate_msr_write(vcpu, MSR_IA32_XSS, kvm_ghcb_get_xss(svm));
3438 
3439 	/* Copy the GHCB exit information into the VMCB fields */
3440 	control->exit_code = kvm_ghcb_get_sw_exit_code(svm);
3441 	control->exit_info_1 = kvm_ghcb_get_sw_exit_info_1(svm);
3442 	control->exit_info_2 = kvm_ghcb_get_sw_exit_info_2(svm);
3443 	svm->sev_es.sw_scratch = kvm_ghcb_get_sw_scratch_if_valid(svm);
3444 
3445 	/* Clear the valid entries fields */
3446 	memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
3447 }
3448 
3449 static bool sev_es_are_required_ghcb_fields_valid(struct vcpu_svm *svm)
3450 {
3451 	struct vmcb_control_area *control = &svm->vmcb->control;
3452 	struct kvm_vcpu *vcpu = &svm->vcpu;
3453 
3454 	if (!kvm_ghcb_sw_exit_code_is_valid(svm) ||
3455 	    !kvm_ghcb_sw_exit_info_1_is_valid(svm) ||
3456 	    !kvm_ghcb_sw_exit_info_2_is_valid(svm))
3457 		return false;
3458 
3459 	switch (control->exit_code) {
3460 	case SVM_EXIT_WRITE_DR7:
3461 		return kvm_ghcb_rax_is_valid(svm);
3462 	case SVM_EXIT_RDPMC:
3463 		return kvm_ghcb_rcx_is_valid(svm);
3464 	case SVM_EXIT_CPUID:
3465 		if (!kvm_ghcb_rax_is_valid(svm) ||
3466 		    !kvm_ghcb_rcx_is_valid(svm))
3467 			return false;
3468 
3469 		return vcpu->arch.regs[VCPU_REGS_RAX] != 0xd ||
3470 		       kvm_ghcb_xcr0_is_valid(svm);
3471 	case SVM_EXIT_IOIO:
3472 		if (control->exit_info_1 & SVM_IOIO_STR_MASK)
3473 			return kvm_ghcb_sw_scratch_is_valid(svm);
3474 
3475 		if (!(control->exit_info_1 & SVM_IOIO_TYPE_MASK))
3476 			return kvm_ghcb_rax_is_valid(svm);
3477 
3478 		return true;
3479 	case SVM_EXIT_MSR:
3480 		if (!kvm_ghcb_rcx_is_valid(svm))
3481 			return false;
3482 
3483 		return !control->exit_info_1 ||
3484 		       (kvm_ghcb_rax_is_valid(svm) && kvm_ghcb_rdx_is_valid(svm));
3485 	case SVM_EXIT_VMMCALL:
3486 		return kvm_ghcb_rax_is_valid(svm) && kvm_ghcb_cpl_is_valid(svm);
3487 	case SVM_EXIT_MONITOR:
3488 		return kvm_ghcb_rax_is_valid(svm) &&
3489 		       kvm_ghcb_rcx_is_valid(svm) &&
3490 		       kvm_ghcb_rdx_is_valid(svm);
3491 	case SVM_EXIT_MWAIT:
3492 		return kvm_ghcb_rax_is_valid(svm) && kvm_ghcb_rcx_is_valid(svm);
3493 	case SVM_VMGEXIT_AP_CREATION:
3494 		return kvm_ghcb_rax_is_valid(svm) ||
3495 		       lower_32_bits(control->exit_info_1) == SVM_VMGEXIT_AP_DESTROY;
3496 		break;
3497 	case SVM_VMGEXIT_MMIO_READ:
3498 	case SVM_VMGEXIT_MMIO_WRITE:
3499 	case SVM_VMGEXIT_PSC:
3500 		return kvm_ghcb_sw_scratch_is_valid(svm);
3501 	default:
3502 		return true;
3503 	}
3504 }
3505 
3506 static void __sev_es_unmap_ghcb(struct vcpu_svm *svm)
3507 {
3508 	if (svm->sev_es.ghcb_sa_free) {
3509 		kvfree(svm->sev_es.ghcb_sa);
3510 		svm->sev_es.ghcb_sa = NULL;
3511 		svm->sev_es.ghcb_sa_free = false;
3512 	}
3513 
3514 	if (svm->sev_es.ghcb) {
3515 		kvm_vcpu_unmap(&svm->vcpu, &svm->sev_es.ghcb_map);
3516 		svm->sev_es.ghcb = NULL;
3517 	}
3518 }
3519 
3520 void sev_es_unmap_ghcb(struct vcpu_svm *svm)
3521 {
3522 	/* Clear any indication that the vCPU is in a type of AP Reset Hold */
3523 	svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NONE;
3524 
3525 	if (!svm->sev_es.ghcb)
3526 		return;
3527 
3528 	/*
3529 	 * If the scratch area lives outside the GHCB, there's a buffer that,
3530 	 * depending on the operation performed, may need to be synced.
3531 	 */
3532 	if (svm->sev_es.ghcb_sa_sync) {
3533 		kvm_write_guest(svm->vcpu.kvm, svm->sev_es.sw_scratch,
3534 				svm->sev_es.ghcb_sa, svm->sev_es.ghcb_sa_len);
3535 		svm->sev_es.ghcb_sa_sync = false;
3536 	}
3537 
3538 	trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->sev_es.ghcb);
3539 
3540 	sev_es_sync_to_ghcb(svm);
3541 
3542 	__sev_es_unmap_ghcb(svm);
3543 }
3544 
3545 void sev_free_vcpu(struct kvm_vcpu *vcpu)
3546 {
3547 	struct vcpu_svm *svm;
3548 
3549 	if (!is_sev_es_guest(vcpu))
3550 		return;
3551 
3552 	svm = to_svm(vcpu);
3553 
3554 	/*
3555 	 * If it's an SNP guest, then the VMSA was marked in the RMP table as
3556 	 * a guest-owned page. Transition the page to hypervisor state before
3557 	 * releasing it back to the system.
3558 	 */
3559 	if (is_sev_snp_guest(vcpu)) {
3560 		u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
3561 
3562 		if (kvm_rmp_make_shared(vcpu->kvm, pfn, PG_LEVEL_4K))
3563 			goto skip_vmsa_free;
3564 	}
3565 
3566 	if (vcpu->arch.guest_state_protected)
3567 		sev_flush_encrypted_page(vcpu, svm->sev_es.vmsa);
3568 
3569 	__free_page(virt_to_page(svm->sev_es.vmsa));
3570 
3571 skip_vmsa_free:
3572 	__sev_es_unmap_ghcb(svm);
3573 }
3574 
3575 bool sev_vcpu_needs_initialization(struct kvm_vcpu *vcpu)
3576 {
3577 	return to_kvm_sev_info(vcpu->kvm)->need_init;
3578 }
3579 
3580 int pre_sev_run(struct vcpu_svm *svm, int cpu)
3581 {
3582 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
3583 	struct kvm_vcpu *vcpu = &svm->vcpu;
3584 	struct kvm *kvm = vcpu->kvm;
3585 	unsigned int asid = sev_get_asid(kvm);
3586 
3587 	/*
3588 	 * Reject KVM_RUN if userspace attempts to run the vCPU with an invalid
3589 	 * VMSA, e.g. if userspace forces the vCPU to be RUNNABLE after an SNP
3590 	 * AP Destroy event.
3591 	 */
3592 	if (is_sev_es_guest(vcpu) && !VALID_PAGE(svm->vmcb->control.vmsa_pa))
3593 		return -EINVAL;
3594 
3595 	/*
3596 	 * To optimize cache flushes when memory is reclaimed from an SEV VM,
3597 	 * track physical CPUs that enter the guest for SEV VMs and thus can
3598 	 * have encrypted, dirty data in the cache, and flush caches only for
3599 	 * CPUs that have entered the guest.
3600 	 */
3601 	if (!cpumask_test_cpu(cpu, to_kvm_sev_info(kvm)->have_run_cpus))
3602 		cpumask_set_cpu(cpu, to_kvm_sev_info(kvm)->have_run_cpus);
3603 
3604 	/* Assign the asid allocated with this SEV guest */
3605 	svm->asid = asid;
3606 
3607 	/*
3608 	 * Flush guest TLB:
3609 	 *
3610 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
3611 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
3612 	 */
3613 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
3614 	    svm->vcpu.arch.last_vmentry_cpu == cpu)
3615 		return 0;
3616 
3617 	sd->sev_vmcbs[asid] = svm->vmcb;
3618 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3619 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3620 	return 0;
3621 }
3622 
3623 #define GHCB_SCRATCH_AREA_LIMIT		(16ULL * PAGE_SIZE)
3624 static int setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 min_len)
3625 {
3626 	struct vmcb_control_area *control = &svm->vmcb->control;
3627 	u64 ghcb_scratch_beg, ghcb_scratch_end;
3628 	u64 scratch_gpa_beg, scratch_gpa_end;
3629 	void *scratch_va;
3630 
3631 	if (WARN_ON_ONCE(!min_len))
3632 		goto e_scratch;
3633 
3634 	scratch_gpa_beg = svm->sev_es.sw_scratch;
3635 	if (!scratch_gpa_beg) {
3636 		pr_err("vmgexit: scratch gpa not provided\n");
3637 		goto e_scratch;
3638 	}
3639 
3640 	scratch_gpa_end = scratch_gpa_beg + min_len;
3641 	if (scratch_gpa_end < scratch_gpa_beg) {
3642 		pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
3643 		       min_len, scratch_gpa_beg);
3644 		goto e_scratch;
3645 	}
3646 
3647 	WARN_ON_ONCE(svm->sev_es.ghcb_sa_sync || svm->sev_es.ghcb_sa_free);
3648 
3649 	if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
3650 		/* Scratch area begins within GHCB */
3651 		ghcb_scratch_beg = control->ghcb_gpa +
3652 				   offsetof(struct ghcb, shared_buffer);
3653 		ghcb_scratch_end = control->ghcb_gpa +
3654 				   offsetof(struct ghcb, reserved_0xff0);
3655 
3656 		/*
3657 		 * If the scratch area begins within the GHCB, it must be
3658 		 * completely contained in the GHCB shared buffer area.
3659 		 */
3660 		if (scratch_gpa_beg < ghcb_scratch_beg ||
3661 		    scratch_gpa_end > ghcb_scratch_end) {
3662 			pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
3663 			       scratch_gpa_beg, scratch_gpa_end);
3664 			goto e_scratch;
3665 		}
3666 
3667 		scratch_va = (void *)svm->sev_es.ghcb;
3668 		scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
3669 
3670 		svm->sev_es.ghcb_sa_sync = false;
3671 		svm->sev_es.ghcb_sa_free = false;
3672 		svm->sev_es.ghcb_sa_len = ghcb_scratch_end - scratch_gpa_beg;
3673 	} else {
3674 		/* GHCB v2 requires the scratch area to be within the GHCB. */
3675 		if (to_kvm_sev_info(svm->vcpu.kvm)->ghcb_version >= 2)
3676 			goto e_scratch;
3677 
3678 		/*
3679 		 * The guest memory must be read into a kernel buffer, so
3680 		 * limit the size
3681 		 */
3682 		if (min_len > GHCB_SCRATCH_AREA_LIMIT) {
3683 			pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
3684 			       min_len, GHCB_SCRATCH_AREA_LIMIT);
3685 			goto e_scratch;
3686 		}
3687 		scratch_va = kvzalloc(min_len, GFP_KERNEL_ACCOUNT);
3688 		if (!scratch_va)
3689 			return -ENOMEM;
3690 
3691 		if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, min_len)) {
3692 			/* Unable to copy scratch area from guest */
3693 			pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
3694 
3695 			kvfree(scratch_va);
3696 			return -EFAULT;
3697 		}
3698 
3699 		/*
3700 		 * The scratch area is outside the GHCB. The operation will
3701 		 * dictate whether the buffer needs to be synced before running
3702 		 * the vCPU next time (i.e. a read was requested so the data
3703 		 * must be written back to the guest memory).
3704 		 */
3705 		svm->sev_es.ghcb_sa_sync = sync;
3706 		svm->sev_es.ghcb_sa_free = true;
3707 		svm->sev_es.ghcb_sa_len = min_len;
3708 	}
3709 
3710 	svm->sev_es.ghcb_sa = scratch_va;
3711 	return 0;
3712 
3713 e_scratch:
3714 	svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_SCRATCH_AREA);
3715 
3716 	return 1;
3717 }
3718 
3719 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
3720 			      unsigned int pos)
3721 {
3722 	svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
3723 	svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
3724 }
3725 
3726 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
3727 {
3728 	return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
3729 }
3730 
3731 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
3732 {
3733 	svm->vmcb->control.ghcb_gpa = value;
3734 }
3735 
3736 static int snp_rmptable_psmash(kvm_pfn_t pfn)
3737 {
3738 	int ret;
3739 
3740 	pfn = pfn & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
3741 
3742 	/*
3743 	 * PSMASH_FAIL_INUSE indicates another processor is modifying the
3744 	 * entry, so retry until that's no longer the case.
3745 	 */
3746 	do {
3747 		ret = psmash(pfn);
3748 	} while (ret == PSMASH_FAIL_INUSE);
3749 
3750 	return ret;
3751 }
3752 
3753 static int snp_complete_psc_msr(struct kvm_vcpu *vcpu)
3754 {
3755 	u64 hypercall_ret = READ_ONCE(vcpu->run->hypercall.ret);
3756 	struct vcpu_svm *svm = to_svm(vcpu);
3757 
3758 	if (!kvm_is_valid_map_gpa_range_ret(hypercall_ret))
3759 		return -EINVAL;
3760 
3761 	if (hypercall_ret)
3762 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3763 	else
3764 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP);
3765 
3766 	return 1; /* resume guest */
3767 }
3768 
3769 static int snp_begin_psc_msr(struct vcpu_svm *svm, u64 ghcb_msr)
3770 {
3771 	u64 gpa = gfn_to_gpa(GHCB_MSR_PSC_REQ_TO_GFN(ghcb_msr));
3772 	u8 op = GHCB_MSR_PSC_REQ_TO_OP(ghcb_msr);
3773 	struct kvm_vcpu *vcpu = &svm->vcpu;
3774 
3775 	if (op != SNP_PAGE_STATE_PRIVATE && op != SNP_PAGE_STATE_SHARED) {
3776 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3777 		return 1; /* resume guest */
3778 	}
3779 
3780 	if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) {
3781 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3782 		return 1; /* resume guest */
3783 	}
3784 
3785 	vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
3786 	vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
3787 	/*
3788 	 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
3789 	 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
3790 	 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
3791 	 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
3792 	 */
3793 	vcpu->run->hypercall.ret = 0;
3794 	vcpu->run->hypercall.args[0] = gpa;
3795 	vcpu->run->hypercall.args[1] = 1;
3796 	vcpu->run->hypercall.args[2] = (op == SNP_PAGE_STATE_PRIVATE)
3797 				       ? KVM_MAP_GPA_RANGE_ENCRYPTED
3798 				       : KVM_MAP_GPA_RANGE_DECRYPTED;
3799 	vcpu->run->hypercall.args[2] |= KVM_MAP_GPA_RANGE_PAGE_SZ_4K;
3800 
3801 	vcpu->arch.complete_userspace_io = snp_complete_psc_msr;
3802 
3803 	return 0; /* forward request to userspace */
3804 }
3805 
3806 struct psc_buffer {
3807 	struct psc_hdr hdr;
3808 	struct psc_entry entries[];
3809 } __packed;
3810 
3811 static int snp_do_psc(struct vcpu_svm *svm);
3812 
3813 static void snp_complete_psc(struct vcpu_svm *svm, u64 psc_ret)
3814 {
3815 	memset(&svm->sev_es.psc, 0, sizeof(svm->sev_es.psc));
3816 
3817 	/*
3818 	 * PSC requests always get a "no action" response in SW_EXITINFO1, with
3819 	 * a PSC-specific return code in SW_EXITINFO2 that provides the "real"
3820 	 * return code.  E.g. if the PSC request was interrupted, the need to
3821 	 * retry is communicated via SW_EXITINFO2, not SW_EXITINFO1.
3822 	 */
3823 	svm_vmgexit_no_action(svm, psc_ret);
3824 }
3825 
3826 static void __snp_complete_one_psc(struct vcpu_svm *svm)
3827 {
3828 	struct vcpu_sev_es_state *sev_es = &svm->sev_es;
3829 	struct psc_buffer *guest_psc = sev_es->ghcb_sa;
3830 	__u16 idx;
3831 
3832 	/*
3833 	 * Everything in-flight has been processed successfully. Update the
3834 	 * corresponding entries in the guest's PSC buffer and zero out the
3835 	 * count of in-flight PSC entries.
3836 	 */
3837 	for (idx = sev_es->psc.cur_idx; sev_es->psc.batch_size;
3838 	     sev_es->psc.batch_size--, idx++) {
3839 		struct psc_entry entry = READ_ONCE(guest_psc->entries[idx]);
3840 
3841 		guest_psc->entries[idx].cur_page = entry.pagesize ? 512 : 1;
3842 	}
3843 
3844 	sev_es->psc.cur_idx = idx;
3845 	guest_psc->hdr.cur_entry = idx;
3846 }
3847 
3848 static int snp_complete_one_psc(struct kvm_vcpu *vcpu)
3849 {
3850 	u64 hypercall_ret = READ_ONCE(vcpu->run->hypercall.ret);
3851 	struct vcpu_svm *svm = to_svm(vcpu);
3852 
3853 	if (!kvm_is_valid_map_gpa_range_ret(hypercall_ret))
3854 		return -EINVAL;
3855 
3856 	if (hypercall_ret) {
3857 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3858 		return 1; /* resume guest */
3859 	}
3860 
3861 	__snp_complete_one_psc(svm);
3862 
3863 	/* Handle the next range (if any). */
3864 	return snp_do_psc(svm);
3865 }
3866 
3867 static int snp_do_psc(struct vcpu_svm *svm)
3868 {
3869 	struct vcpu_sev_es_state *sev_es = &svm->sev_es;
3870 	struct psc_buffer *guest_psc = sev_es->ghcb_sa;
3871 	struct kvm_vcpu *vcpu = &svm->vcpu;
3872 	struct psc_entry entry_start;
3873 	int npages;
3874 	bool huge;
3875 	u64 gfn;
3876 	u16 idx;
3877 
3878 next_range:
3879 	/* There should be no other PSCs in-flight at this point. */
3880 	if (WARN_ON_ONCE(svm->sev_es.psc.batch_size)) {
3881 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3882 		return 1;
3883 	}
3884 
3885 	/* Find the start of the next range which needs processing. */
3886 	for (idx = sev_es->psc.cur_idx; idx <= sev_es->psc.end_idx; idx++) {
3887 		entry_start = READ_ONCE(guest_psc->entries[idx]);
3888 
3889 		gfn = entry_start.gfn;
3890 		huge = entry_start.pagesize;
3891 		npages = huge ? 512 : 1;
3892 
3893 		if (entry_start.cur_page > npages || !IS_ALIGNED(gfn, npages)) {
3894 			snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_ENTRY);
3895 			return 1;
3896 		}
3897 
3898 		if (entry_start.cur_page) {
3899 			/*
3900 			 * If this is a partially-completed 2M range, force 4K handling
3901 			 * for the remaining pages since they're effectively split at
3902 			 * this point. Subsequent code should ensure this doesn't get
3903 			 * combined with adjacent PSC entries where 2M handling is still
3904 			 * possible.
3905 			 */
3906 			npages -= entry_start.cur_page;
3907 			gfn += entry_start.cur_page;
3908 			huge = false;
3909 		}
3910 
3911 		if (npages)
3912 			break;
3913 
3914 		/*
3915 		 * Increment the guest-visible index to communicate the current
3916 		 * entry back to the guest, e.g. in case of failure.  No need
3917 		 * for READ_ONCE() as KVM doesn't consume the field, i.e. a
3918 		 * misbehaving guest can only break itself.
3919 		 */
3920 		guest_psc->hdr.cur_entry++;
3921 	}
3922 
3923 	if (idx > sev_es->psc.end_idx) {
3924 		/* Nothing more to process. */
3925 		snp_complete_psc(svm, 0);
3926 		return 1;
3927 	}
3928 
3929 	sev_es->psc.is_2m = huge;
3930 	sev_es->psc.cur_idx = idx;
3931 	sev_es->psc.batch_size = 1;
3932 
3933 	/*
3934 	 * Find all subsequent PSC entries that contain adjacent GPA
3935 	 * ranges/operations and can be combined into a single
3936 	 * KVM_HC_MAP_GPA_RANGE exit.
3937 	 */
3938 	while (++idx <= sev_es->psc.end_idx) {
3939 		struct psc_entry entry = READ_ONCE(guest_psc->entries[idx]);
3940 
3941 		if (entry.operation != entry_start.operation ||
3942 		    entry.gfn != entry_start.gfn + npages ||
3943 		    entry.cur_page || !!entry.pagesize != huge)
3944 			break;
3945 
3946 		sev_es->psc.batch_size++;
3947 		npages += huge ? 512 : 1;
3948 	}
3949 
3950 	switch (entry_start.operation) {
3951 	case VMGEXIT_PSC_OP_PRIVATE:
3952 	case VMGEXIT_PSC_OP_SHARED:
3953 		vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
3954 		vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
3955 		/*
3956 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
3957 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
3958 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
3959 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
3960 		 */
3961 		vcpu->run->hypercall.ret = 0;
3962 		vcpu->run->hypercall.args[0] = gfn_to_gpa(gfn);
3963 		vcpu->run->hypercall.args[1] = npages;
3964 		vcpu->run->hypercall.args[2] = entry_start.operation == VMGEXIT_PSC_OP_PRIVATE
3965 					       ? KVM_MAP_GPA_RANGE_ENCRYPTED
3966 					       : KVM_MAP_GPA_RANGE_DECRYPTED;
3967 		vcpu->run->hypercall.args[2] |= entry_start.pagesize
3968 						? KVM_MAP_GPA_RANGE_PAGE_SZ_2M
3969 						: KVM_MAP_GPA_RANGE_PAGE_SZ_4K;
3970 		vcpu->arch.complete_userspace_io = snp_complete_one_psc;
3971 		return 0; /* forward request to userspace */
3972 	default:
3973 		/*
3974 		 * Only shared/private PSC operations are currently supported, so if the
3975 		 * entire range consists of unsupported operations (e.g. SMASH/UNSMASH),
3976 		 * then consider the entire range completed and avoid exiting to
3977 		 * userspace. In theory snp_complete_psc() can always be called directly
3978 		 * at this point to complete the current range and start the next one,
3979 		 * but that could lead to unexpected levels of recursion.
3980 		 */
3981 		__snp_complete_one_psc(svm);
3982 		goto next_range;
3983 	}
3984 
3985 	BUG();
3986 }
3987 
3988 static int snp_begin_psc(struct vcpu_svm *svm)
3989 {
3990 	struct vcpu_sev_es_state *sev_es = &svm->sev_es;
3991 	struct psc_buffer *guest_psc = sev_es->ghcb_sa;
3992 	u16 max_nr_entries;
3993 
3994 	if (!user_exit_on_hypercall(svm->vcpu.kvm, KVM_HC_MAP_GPA_RANGE)) {
3995 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3996 		return 1;
3997 	}
3998 
3999 	/*
4000 	 * GHCB v2 requires the scratch area to reside within the GHCB itself,
4001 	 * and PSC requests are only supported for GHCB v2+.  Thus it should be
4002 	 * impossible to exceed the max PSC entry count (which is derived from
4003 	 * the size of the shared GHCB buffer).
4004 	 */
4005 	max_nr_entries = (sev_es->ghcb_sa_len - sizeof(struct psc_hdr)) /
4006 			 sizeof(struct psc_entry);
4007 	if (WARN_ON_ONCE(max_nr_entries > VMGEXIT_PSC_MAX_COUNT)) {
4008 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
4009 		return 1;
4010 	}
4011 
4012 	/*
4013 	 * The PSC descriptor buffer can be modified by a misbehaved guest after
4014 	 * validation, so take care to only use validated copies of values used
4015 	 * for things like array indexing.
4016 	 */
4017 	sev_es->psc.cur_idx = READ_ONCE(guest_psc->hdr.cur_entry);
4018 	sev_es->psc.end_idx = READ_ONCE(guest_psc->hdr.end_entry);
4019 
4020 	if (sev_es->psc.end_idx >= max_nr_entries) {
4021 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_HDR);
4022 		return 1;
4023 	}
4024 
4025 	return snp_do_psc(svm);
4026 }
4027 
4028 static void __sev_snp_reload_vmsa(struct kvm_vcpu *vcpu, gpa_t gpa)
4029 {
4030 	struct vcpu_svm *svm = to_svm(vcpu);
4031 	struct kvm_memory_slot *slot;
4032 	struct kvm *kvm = vcpu->kvm;
4033 	gfn_t gfn = gpa_to_gfn(gpa);
4034 	unsigned long mmu_seq;
4035 	struct page *page;
4036 	kvm_pfn_t pfn;
4037 
4038 	lockdep_assert_held(&svm->sev_es.snp_vmsa_mutex);
4039 
4040 	/*
4041 	 * Clear use of the VMSA.  Ensure snp_guest_vmsa_gpa is written exactly
4042 	 * once, as it is read locklessly when responding to gfn invalidations.
4043 	 * Pairs with the READ_ONCE() in sev_gmem_invalidate_range().
4044 	 */
4045 	svm->vmcb->control.vmsa_pa = INVALID_PAGE;
4046 	WRITE_ONCE(svm->sev_es.snp_guest_vmsa_gpa, INVALID_PAGE);
4047 
4048 	/*
4049 	 * When replacing the VMSA during SEV-SNP AP creation,
4050 	 * mark the VMCB dirty so that full state is always reloaded.
4051 	 */
4052 	vmcb_mark_all_dirty(svm->vmcb);
4053 
4054 	/*
4055 	 * From this point forward, the VMSA will always be a guest-mapped page
4056 	 * rather than the initial one allocated by KVM in svm->sev_es.vmsa. In
4057 	 * theory, svm->sev_es.vmsa could be free'd and cleaned up here, but
4058 	 * that involves cleanups like flushing caches, which would ideally be
4059 	 * handled during teardown rather than guest boot.  Deferring that also
4060 	 * allows the existing logic for SEV-ES VMSAs to be re-used with
4061 	 * minimal SNP-specific changes.
4062 	 */
4063 	svm->sev_es.snp_has_guest_vmsa = true;
4064 
4065 	if (!VALID_PAGE(gpa))
4066 		return;
4067 
4068 	slot = gfn_to_memslot(vcpu->kvm, gfn);
4069 	if (!slot)
4070 		return;
4071 
4072 	mmu_seq = kvm->mmu_invalidate_seq;
4073 	smp_rmb();
4074 
4075 	/*
4076 	 * The new VMSA will be private memory guest memory, so retrieve the
4077 	 * PFN from the gmem backend.
4078 	 */
4079 	if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL))
4080 		return;
4081 
4082 	read_lock(&kvm->mmu_lock);
4083 	/*
4084 	 * Save the guest-provided GPA.  If retry is needed, then KVM will try
4085 	 * again with the same GPA.  If the VMSA is usable, then KVM needs to
4086 	 * track the GPA so that the VMSA can be reloaded if the backing page
4087 	 * for the GPA is invalidated.
4088 	 */
4089 	svm->sev_es.snp_guest_vmsa_gpa = gpa;
4090 	if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn))
4091 		kvm_make_request(KVM_REQ_VMSA_PAGE_RELOAD, vcpu);
4092 	else
4093 		svm->vmcb->control.vmsa_pa = pfn_to_hpa(pfn);
4094 	read_unlock(&kvm->mmu_lock);
4095 
4096 	kvm_release_page_clean(page);
4097 }
4098 
4099 /*
4100  * Invoked as part of svm_vcpu_reset() processing of an init event.
4101  */
4102 static void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu)
4103 {
4104 	struct vcpu_svm *svm = to_svm(vcpu);
4105 	gpa_t gpa;
4106 
4107 	guard(mutex)(&svm->sev_es.snp_vmsa_mutex);
4108 
4109 	if (!svm->sev_es.snp_ap_waiting_for_reset)
4110 		return;
4111 
4112 	svm->sev_es.snp_ap_waiting_for_reset = false;
4113 
4114 	/* Mark the vCPU as offline and not runnable */
4115 	vcpu->arch.pv.pv_unhalted = false;
4116 	kvm_set_mp_state(vcpu, KVM_MP_STATE_HALTED);
4117 
4118 	gpa = svm->sev_es.snp_pending_vmsa_gpa;
4119 	svm->sev_es.snp_pending_vmsa_gpa = INVALID_PAGE;
4120 
4121 	__sev_snp_reload_vmsa(vcpu, gpa);
4122 
4123 	/*
4124 	 * Mark the vCPU as runnable for CREATE requests, indicated by a valid
4125 	 * VMSA GPA, even if installing the VMSA failed, so that KVM_RUN will
4126 	 * fail instead of blocking indefinitely and hanging the vCPU, e.g. if
4127 	 * the backing guest_memfd page is unavailable.
4128 	 */
4129 	if (VALID_PAGE(gpa))
4130 		kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
4131 }
4132 
4133 void sev_snp_reload_vmsa(struct kvm_vcpu *vcpu)
4134 {
4135 	struct vcpu_sev_es_state *sev_es = &to_svm(vcpu)->sev_es;
4136 
4137 	guard(mutex)(&sev_es->snp_vmsa_mutex);
4138 
4139 	__sev_snp_reload_vmsa(vcpu, sev_es->snp_guest_vmsa_gpa);
4140 }
4141 
4142 static int sev_snp_ap_creation(struct vcpu_svm *svm)
4143 {
4144 	struct kvm_sev_info *sev = to_kvm_sev_info(svm->vcpu.kvm);
4145 	struct kvm_vcpu *vcpu = &svm->vcpu;
4146 	struct kvm_vcpu *target_vcpu;
4147 	struct vcpu_svm *target_svm;
4148 	unsigned int request;
4149 	unsigned int apic_id;
4150 
4151 	request = lower_32_bits(svm->vmcb->control.exit_info_1);
4152 	apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
4153 
4154 	/* Validate the APIC ID */
4155 	target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);
4156 	if (!target_vcpu) {
4157 		vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
4158 			    apic_id);
4159 		return -EINVAL;
4160 	}
4161 
4162 	target_svm = to_svm(target_vcpu);
4163 
4164 	guard(mutex)(&target_svm->sev_es.snp_vmsa_mutex);
4165 
4166 	switch (request) {
4167 	case SVM_VMGEXIT_AP_CREATE_ON_INIT:
4168 	case SVM_VMGEXIT_AP_CREATE:
4169 		if (vcpu->arch.regs[VCPU_REGS_RAX] != sev->vmsa_features) {
4170 			vcpu_unimpl(vcpu, "vmgexit: mismatched AP sev_features [%#lx] != [%#llx] from guest\n",
4171 				    vcpu->arch.regs[VCPU_REGS_RAX], sev->vmsa_features);
4172 			return -EINVAL;
4173 		}
4174 
4175 		if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
4176 			vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
4177 				    svm->vmcb->control.exit_info_2);
4178 			return -EINVAL;
4179 		}
4180 
4181 		/*
4182 		 * Malicious guest can RMPADJUST a large page into VMSA which
4183 		 * will hit the SNP erratum where the CPU will incorrectly signal
4184 		 * an RMP violation #PF if a hugepage collides with the RMP entry
4185 		 * of VMSA page, reject the AP CREATE request if VMSA address from
4186 		 * guest is 2M aligned.
4187 		 */
4188 		if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
4189 			vcpu_unimpl(vcpu,
4190 				    "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
4191 				    svm->vmcb->control.exit_info_2);
4192 			return -EINVAL;
4193 		}
4194 
4195 		target_svm->sev_es.snp_pending_vmsa_gpa = svm->vmcb->control.exit_info_2;
4196 		break;
4197 	case SVM_VMGEXIT_AP_DESTROY:
4198 		target_svm->sev_es.snp_pending_vmsa_gpa = INVALID_PAGE;
4199 		break;
4200 	default:
4201 		vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
4202 			    request);
4203 		return -EINVAL;
4204 	}
4205 
4206 	target_svm->sev_es.snp_ap_waiting_for_reset = true;
4207 
4208 	/*
4209 	 * Unless Creation is deferred until INIT, signal the vCPU to update
4210 	 * its state.
4211 	 */
4212 	if (request != SVM_VMGEXIT_AP_CREATE_ON_INIT)
4213 		kvm_make_request_and_kick(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
4214 
4215 	return 0;
4216 }
4217 
4218 static int snp_handle_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
4219 {
4220 	struct sev_data_snp_guest_request data = {0};
4221 	struct kvm *kvm = svm->vcpu.kvm;
4222 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
4223 	sev_ret_code fw_err = 0;
4224 	int ret;
4225 
4226 	if (!is_sev_snp_guest(&svm->vcpu))
4227 		return -EINVAL;
4228 
4229 	guard(mutex)(&sev->guest_req_mutex);
4230 
4231 	if (kvm_read_guest(kvm, req_gpa, sev->guest_req_buf, PAGE_SIZE))
4232 		return -EIO;
4233 
4234 	data.gctx_paddr = __psp_pa(sev->snp_context);
4235 	data.req_paddr = __psp_pa(sev->guest_req_buf);
4236 	data.res_paddr = __psp_pa(sev->guest_resp_buf);
4237 
4238 	/*
4239 	 * Firmware failures are propagated on to guest, but any other failure
4240 	 * condition along the way should be reported to userspace. E.g. if
4241 	 * the PSP is dead and commands are timing out.
4242 	 */
4243 	ret = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &fw_err);
4244 	if (ret && !fw_err)
4245 		return ret;
4246 
4247 	if (kvm_write_guest(kvm, resp_gpa, sev->guest_resp_buf, PAGE_SIZE))
4248 		return -EIO;
4249 
4250 	/* No action is requested *from KVM* if there was a firmware error. */
4251 	svm_vmgexit_no_action(svm, SNP_GUEST_ERR(0, fw_err));
4252 
4253 	/* resume guest */
4254 	return 1;
4255 }
4256 
4257 static int snp_req_certs_err(struct vcpu_svm *svm, u32 vmm_error)
4258 {
4259 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, SNP_GUEST_ERR(vmm_error, 0));
4260 
4261 	return 1; /* resume guest */
4262 }
4263 
4264 static int snp_complete_req_certs(struct kvm_vcpu *vcpu)
4265 {
4266 	struct vcpu_svm *svm = to_svm(vcpu);
4267 	struct vmcb_control_area *control = &svm->vmcb->control;
4268 
4269 	switch (READ_ONCE(vcpu->run->snp_req_certs.ret)) {
4270 	case 0:
4271 		return snp_handle_guest_req(svm, control->exit_info_1,
4272 					    control->exit_info_2);
4273 	case ENOSPC:
4274 		vcpu->arch.regs[VCPU_REGS_RBX] = vcpu->run->snp_req_certs.npages;
4275 		return snp_req_certs_err(svm, SNP_GUEST_VMM_ERR_INVALID_LEN);
4276 	case EAGAIN:
4277 		return snp_req_certs_err(svm, SNP_GUEST_VMM_ERR_BUSY);
4278 	case EIO:
4279 		return snp_req_certs_err(svm, SNP_GUEST_VMM_ERR_GENERIC);
4280 	default:
4281 		break;
4282 	}
4283 
4284 	return -EINVAL;
4285 }
4286 
4287 static int snp_handle_ext_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
4288 {
4289 	struct kvm_vcpu *vcpu = &svm->vcpu;
4290 	struct kvm *kvm = vcpu->kvm;
4291 
4292 	u8 msg_type;
4293 
4294 	if (!is_sev_snp_guest(vcpu))
4295 		return -EINVAL;
4296 
4297 	if (kvm_read_guest(kvm, req_gpa + offsetof(struct snp_guest_msg_hdr, msg_type),
4298 			   &msg_type, 1))
4299 		return -EIO;
4300 
4301 	/*
4302 	 * As per GHCB spec, requests of type MSG_REPORT_REQ also allow for
4303 	 * additional certificate data to be provided alongside the attestation
4304 	 * report via the guest-provided data pages indicated by RAX/RBX. If
4305 	 * userspace enables KVM_EXIT_SNP_REQ_CERTS, then exit to userspace
4306 	 * to give userspace an opportunity to provide the certificate data
4307 	 * before issuing/completing the attestation request. Otherwise, return
4308 	 * an empty certificate table in the guest-provided data pages and
4309 	 * handle the attestation request immediately.
4310 	 */
4311 	if (msg_type == SNP_MSG_REPORT_REQ) {
4312 		struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
4313 		u64 data_npages;
4314 		gpa_t data_gpa;
4315 
4316 		if (!kvm_ghcb_rax_is_valid(svm) || !kvm_ghcb_rbx_is_valid(svm))
4317 			goto request_invalid;
4318 
4319 		data_gpa = vcpu->arch.regs[VCPU_REGS_RAX];
4320 		data_npages = vcpu->arch.regs[VCPU_REGS_RBX];
4321 
4322 		if (!PAGE_ALIGNED(data_gpa))
4323 			goto request_invalid;
4324 
4325 		if (sev->snp_certs_enabled) {
4326 			vcpu->run->exit_reason = KVM_EXIT_SNP_REQ_CERTS;
4327 			vcpu->run->snp_req_certs.gpa = data_gpa;
4328 			vcpu->run->snp_req_certs.npages = data_npages;
4329 			vcpu->run->snp_req_certs.ret = 0;
4330 			vcpu->arch.complete_userspace_io = snp_complete_req_certs;
4331 			return 0;
4332 		}
4333 
4334 		/*
4335 		 * As per GHCB spec (see "SNP Extended Guest Request"), the
4336 		 * certificate table is terminated by 24-bytes of zeroes.
4337 		 */
4338 		if (data_npages && kvm_clear_guest(kvm, data_gpa, 24))
4339 			return -EIO;
4340 	}
4341 
4342 	return snp_handle_guest_req(svm, req_gpa, resp_gpa);
4343 
4344 request_invalid:
4345 	svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4346 	return 1; /* resume guest */
4347 }
4348 
4349 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
4350 {
4351 	struct vmcb_control_area *control = &svm->vmcb->control;
4352 	struct kvm_vcpu *vcpu = &svm->vcpu;
4353 	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
4354 	u64 ghcb_info;
4355 	int ret = 1;
4356 
4357 	ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
4358 
4359 	trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
4360 					     control->ghcb_gpa);
4361 
4362 	switch (ghcb_info) {
4363 	case GHCB_MSR_SEV_INFO_REQ:
4364 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version,
4365 						    GHCB_VERSION_MIN,
4366 						    sev_enc_bit));
4367 		break;
4368 	case GHCB_MSR_CPUID_REQ: {
4369 		u64 cpuid_fn, cpuid_reg, cpuid_value;
4370 
4371 		cpuid_fn = get_ghcb_msr_bits(svm,
4372 					     GHCB_MSR_CPUID_FUNC_MASK,
4373 					     GHCB_MSR_CPUID_FUNC_POS);
4374 
4375 		/* Initialize the registers needed by the CPUID intercept */
4376 		vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
4377 		vcpu->arch.regs[VCPU_REGS_RCX] = 0;
4378 
4379 		ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
4380 		if (!ret) {
4381 			/* Error, keep GHCB MSR value as-is */
4382 			break;
4383 		}
4384 
4385 		cpuid_reg = get_ghcb_msr_bits(svm,
4386 					      GHCB_MSR_CPUID_REG_MASK,
4387 					      GHCB_MSR_CPUID_REG_POS);
4388 		if (cpuid_reg == 0)
4389 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
4390 		else if (cpuid_reg == 1)
4391 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
4392 		else if (cpuid_reg == 2)
4393 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
4394 		else
4395 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
4396 
4397 		set_ghcb_msr_bits(svm, cpuid_value,
4398 				  GHCB_MSR_CPUID_VALUE_MASK,
4399 				  GHCB_MSR_CPUID_VALUE_POS);
4400 
4401 		set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
4402 				  GHCB_MSR_INFO_MASK,
4403 				  GHCB_MSR_INFO_POS);
4404 		break;
4405 	}
4406 	case GHCB_MSR_AP_RESET_HOLD_REQ:
4407 		svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_MSR_PROTO;
4408 		ret = kvm_emulate_ap_reset_hold(&svm->vcpu);
4409 
4410 		/*
4411 		 * Preset the result to a non-SIPI return and then only set
4412 		 * the result to non-zero when delivering a SIPI.
4413 		 */
4414 		set_ghcb_msr_bits(svm, 0,
4415 				  GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,
4416 				  GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
4417 
4418 		set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP,
4419 				  GHCB_MSR_INFO_MASK,
4420 				  GHCB_MSR_INFO_POS);
4421 		break;
4422 	case GHCB_MSR_HV_FT_REQ:
4423 		set_ghcb_msr_bits(svm, GHCB_HV_FT_SUPPORTED,
4424 				  GHCB_MSR_HV_FT_MASK, GHCB_MSR_HV_FT_POS);
4425 		set_ghcb_msr_bits(svm, GHCB_MSR_HV_FT_RESP,
4426 				  GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
4427 		break;
4428 	case GHCB_MSR_PREF_GPA_REQ:
4429 		if (!is_sev_snp_guest(vcpu))
4430 			goto out_terminate;
4431 
4432 		set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_NONE, GHCB_MSR_GPA_VALUE_MASK,
4433 				  GHCB_MSR_GPA_VALUE_POS);
4434 		set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_RESP, GHCB_MSR_INFO_MASK,
4435 				  GHCB_MSR_INFO_POS);
4436 		break;
4437 	case GHCB_MSR_REG_GPA_REQ: {
4438 		u64 gfn;
4439 
4440 		if (!is_sev_snp_guest(vcpu))
4441 			goto out_terminate;
4442 
4443 		gfn = get_ghcb_msr_bits(svm, GHCB_MSR_GPA_VALUE_MASK,
4444 					GHCB_MSR_GPA_VALUE_POS);
4445 
4446 		svm->sev_es.ghcb_registered_gpa = gfn_to_gpa(gfn);
4447 
4448 		set_ghcb_msr_bits(svm, gfn, GHCB_MSR_GPA_VALUE_MASK,
4449 				  GHCB_MSR_GPA_VALUE_POS);
4450 		set_ghcb_msr_bits(svm, GHCB_MSR_REG_GPA_RESP, GHCB_MSR_INFO_MASK,
4451 				  GHCB_MSR_INFO_POS);
4452 		break;
4453 	}
4454 	case GHCB_MSR_PSC_REQ:
4455 		if (!is_sev_snp_guest(vcpu))
4456 			goto out_terminate;
4457 
4458 		ret = snp_begin_psc_msr(svm, control->ghcb_gpa);
4459 		break;
4460 	case GHCB_MSR_TERM_REQ: {
4461 		u64 reason_set, reason_code;
4462 
4463 		reason_set = get_ghcb_msr_bits(svm,
4464 					       GHCB_MSR_TERM_REASON_SET_MASK,
4465 					       GHCB_MSR_TERM_REASON_SET_POS);
4466 		reason_code = get_ghcb_msr_bits(svm,
4467 						GHCB_MSR_TERM_REASON_MASK,
4468 						GHCB_MSR_TERM_REASON_POS);
4469 		pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
4470 			reason_set, reason_code);
4471 
4472 		goto out_terminate;
4473 	}
4474 	default:
4475 		/* Error, keep GHCB MSR value as-is */
4476 		break;
4477 	}
4478 
4479 	trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
4480 					    control->ghcb_gpa, ret);
4481 
4482 	return ret;
4483 
4484 out_terminate:
4485 	vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
4486 	vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
4487 	vcpu->run->system_event.ndata = 1;
4488 	vcpu->run->system_event.data[0] = control->ghcb_gpa;
4489 
4490 	return 0;
4491 }
4492 
4493 static bool is_snp_only_vmgexit(u64 exit_code)
4494 {
4495 	switch (exit_code) {
4496 	case SVM_VMGEXIT_AP_CREATION:
4497 	case SVM_VMGEXIT_GUEST_REQUEST:
4498 	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
4499 	case SVM_VMGEXIT_PSC:
4500 		return true;
4501 	default:
4502 		return false;
4503 	}
4504 }
4505 
4506 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
4507 {
4508 	struct vcpu_svm *svm = to_svm(vcpu);
4509 	struct vmcb_control_area *control = &svm->vmcb->control;
4510 	u64 ghcb_gpa;
4511 
4512 	/* Validate the GHCB */
4513 	ghcb_gpa = control->ghcb_gpa;
4514 	if (ghcb_gpa & GHCB_MSR_INFO_MASK)
4515 		return sev_handle_vmgexit_msr_protocol(svm);
4516 
4517 	if (!ghcb_gpa) {
4518 		vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n");
4519 
4520 		/* Without a GHCB, just return right back to the guest */
4521 		return 1;
4522 	}
4523 
4524 	if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->sev_es.ghcb_map)) {
4525 		/* Unable to map GHCB from guest */
4526 		vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
4527 			    ghcb_gpa);
4528 
4529 		/* Without a GHCB, just return right back to the guest */
4530 		return 1;
4531 	}
4532 
4533 	svm->sev_es.ghcb = svm->sev_es.ghcb_map.hva;
4534 
4535 	trace_kvm_vmgexit_enter(vcpu->vcpu_id, svm->sev_es.ghcb);
4536 
4537 	sev_es_sync_from_ghcb(svm);
4538 
4539 	/* SEV-SNP guest requires that the GHCB GPA must be registered */
4540 	if (is_sev_snp_guest(vcpu) &&
4541 	    !ghcb_gpa_is_registered(svm, control->ghcb_gpa)) {
4542 		vcpu_unimpl(vcpu, "vmgexit: GHCB GPA [%#llx] is not registered.\n",
4543 			    control->ghcb_gpa);
4544 		svm_vmgexit_bad_input(svm, GHCB_ERR_NOT_REGISTERED);
4545 		return 1;
4546 	}
4547 
4548 	/* Only GHCB Usage code 0 is supported */
4549 	if (svm->sev_es.ghcb->ghcb_usage) {
4550 		vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
4551 			    svm->sev_es.ghcb->ghcb_usage);
4552 		svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_USAGE);
4553 		return 1;
4554 	}
4555 
4556 	if (is_snp_only_vmgexit(control->exit_code) && !is_sev_snp_guest(vcpu)) {
4557 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is SNP-only\n",
4558 			    control->exit_code);
4559 		svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_EVENT);
4560 		return 1;
4561 	}
4562 
4563 	if (!sev_es_are_required_ghcb_fields_valid(svm)) {
4564 		/*
4565 		 * Print the exit code even though it may not be marked valid
4566 		 * as it could help with debugging.
4567 		 */
4568 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx input is not valid\n",
4569 			    control->exit_code);
4570 		dump_ghcb(svm);
4571 		svm_vmgexit_bad_input(svm, GHCB_ERR_MISSING_INPUT);
4572 		return 1;
4573 	}
4574 
4575 	svm_vmgexit_success(svm, 0);
4576 
4577 	switch (control->exit_code) {
4578 	case SVM_EXIT_IOIO:
4579 		if (!((control->exit_info_1 & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT))
4580 			return 1;
4581 
4582 		fallthrough;
4583 	case SVM_EXIT_READ_DR7:
4584 	case SVM_EXIT_WRITE_DR7:
4585 	case SVM_EXIT_RDTSC:
4586 	case SVM_EXIT_RDTSCP:
4587 	case SVM_EXIT_RDPMC:
4588 	case SVM_EXIT_CPUID:
4589 	case SVM_EXIT_INVD:
4590 	case SVM_EXIT_MSR:
4591 	case SVM_EXIT_VMMCALL:
4592 	case SVM_EXIT_WBINVD:
4593 	case SVM_EXIT_MONITOR:
4594 	case SVM_EXIT_MWAIT:
4595 		return svm_invoke_exit_handler(vcpu, control->exit_code);
4596 	case SVM_VMGEXIT_MMIO_READ:
4597 	case SVM_VMGEXIT_MMIO_WRITE: {
4598 		bool is_write = control->exit_code == SVM_VMGEXIT_MMIO_WRITE;
4599 		u64 len = control->exit_info_2;
4600 		int r;
4601 
4602 		if (!len)
4603 			return 1;
4604 
4605 		if (to_kvm_sev_info(vcpu->kvm)->ghcb_version >= 2 && len > 8) {
4606 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4607 			return 1;
4608 		}
4609 
4610 		r = setup_vmgexit_scratch(svm, !is_write, len);
4611 		if (r)
4612 			return r;
4613 
4614 		return kvm_sev_es_mmio(vcpu, is_write, control->exit_info_1, len,
4615 				       svm->sev_es.ghcb_sa);
4616 	}
4617 	case SVM_VMGEXIT_NMI_COMPLETE:
4618 		++vcpu->stat.nmi_window_exits;
4619 		svm->nmi_masked = false;
4620 		kvm_make_request(KVM_REQ_EVENT, vcpu);
4621 		return 1;
4622 	case SVM_VMGEXIT_AP_HLT_LOOP:
4623 		svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NAE_EVENT;
4624 		return kvm_emulate_ap_reset_hold(vcpu);
4625 	case SVM_VMGEXIT_AP_JUMP_TABLE: {
4626 		struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
4627 
4628 		switch (control->exit_info_1) {
4629 		case 0:
4630 			/* Set AP jump table address */
4631 			sev->ap_jump_table = control->exit_info_2;
4632 			break;
4633 		case 1:
4634 			/* Get AP jump table address */
4635 			svm_vmgexit_success(svm, sev->ap_jump_table);
4636 			break;
4637 		default:
4638 			pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
4639 			       control->exit_info_1);
4640 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4641 		}
4642 		return 1;
4643 	}
4644 	case SVM_VMGEXIT_HV_FEATURES:
4645 		svm_vmgexit_success(svm, GHCB_HV_FT_SUPPORTED);
4646 		return 1;
4647 	case SVM_VMGEXIT_TERM_REQUEST:
4648 		pr_info("SEV-ES guest requested termination: reason %#llx info %#llx\n",
4649 			control->exit_info_1, control->exit_info_2);
4650 		vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
4651 		vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
4652 		vcpu->run->system_event.ndata = 1;
4653 		vcpu->run->system_event.data[0] = control->ghcb_gpa;
4654 		return 0;
4655 	case SVM_VMGEXIT_PSC: {
4656 		int r;
4657 
4658 		r = setup_vmgexit_scratch(svm, true, sizeof(struct psc_hdr));
4659 		if (r)
4660 			return r;
4661 
4662 		return snp_begin_psc(svm);
4663 	}
4664 	case SVM_VMGEXIT_AP_CREATION:
4665 		if (sev_snp_ap_creation(svm))
4666 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4667 		return 1;
4668 	case SVM_VMGEXIT_GUEST_REQUEST:
4669 	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
4670 		if (!PAGE_ALIGNED(control->exit_info_1) ||
4671 		    !PAGE_ALIGNED(control->exit_info_2) ||
4672 		    control->exit_info_1 == control->exit_info_2) {
4673 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4674 			return 1;
4675 		}
4676 
4677 		if (control->exit_code == SVM_VMGEXIT_GUEST_REQUEST)
4678 			return snp_handle_guest_req(svm, control->exit_info_1,
4679 						    control->exit_info_2);
4680 
4681 		return snp_handle_ext_guest_req(svm, control->exit_info_1,
4682 						control->exit_info_2);
4683 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
4684 		/*
4685 		 * Note, the _guest_ is reporting an unsupported #VC, i.e. this
4686 		 * isn't the same thing as KVM getting an unsupported #VMGEXIT.
4687 		 */
4688 		vcpu_unimpl(vcpu,
4689 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
4690 			    control->exit_info_1, control->exit_info_2);
4691 		return -EINVAL;
4692 	default:
4693 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is not valid\n",
4694 			    control->exit_code);
4695 		svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_EVENT);
4696 		return 1;
4697 	}
4698 
4699 	KVM_BUG_ON(1, vcpu->kvm);
4700 	return -EIO;
4701 }
4702 
4703 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
4704 {
4705 	int count;
4706 	int bytes;
4707 	int r;
4708 
4709 	if (svm->vmcb->control.exit_info_2 > INT_MAX)
4710 		return -EINVAL;
4711 
4712 	count = svm->vmcb->control.exit_info_2;
4713 	if (unlikely(check_mul_overflow(count, size, &bytes)))
4714 		return -EINVAL;
4715 
4716 	if (!bytes)
4717 		return 1;
4718 
4719 	r = setup_vmgexit_scratch(svm, in, bytes);
4720 	if (r)
4721 		return r;
4722 
4723 	return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->sev_es.ghcb_sa,
4724 				    count, in);
4725 }
4726 
4727 void sev_es_recalc_msr_intercepts(struct kvm_vcpu *vcpu)
4728 {
4729 	/* Clear intercepts on MSRs that are context switched by hardware. */
4730 	svm_disable_intercept_for_msr(vcpu, MSR_AMD64_SEV_ES_GHCB, MSR_TYPE_RW);
4731 	svm_disable_intercept_for_msr(vcpu, MSR_EFER, MSR_TYPE_RW);
4732 	svm_disable_intercept_for_msr(vcpu, MSR_IA32_CR_PAT, MSR_TYPE_RW);
4733 
4734 	if (boot_cpu_has(X86_FEATURE_V_TSC_AUX))
4735 		svm_set_intercept_for_msr(vcpu, MSR_TSC_AUX, MSR_TYPE_RW,
4736 					  !guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) &&
4737 					  !guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID));
4738 
4739 	svm_set_intercept_for_msr(vcpu, MSR_AMD64_GUEST_TSC_FREQ, MSR_TYPE_R,
4740 				  !snp_is_secure_tsc_enabled(vcpu->kvm));
4741 
4742 	/*
4743 	 * For SEV-ES, accesses to MSR_IA32_XSS should not be intercepted if
4744 	 * the host/guest supports its use.
4745 	 *
4746 	 * KVM treats the guest as being capable of using XSAVES even if XSAVES
4747 	 * isn't enabled in guest CPUID as there is no intercept for XSAVES,
4748 	 * i.e. the guest can use XSAVES/XRSTOR to read/write XSS if XSAVE is
4749 	 * exposed to the guest and XSAVES is supported in hardware.  Condition
4750 	 * full XSS passthrough on the guest being able to use XSAVES *and*
4751 	 * XSAVES being exposed to the guest so that KVM can at least honor
4752 	 * guest CPUID for RDMSR and WRMSR.
4753 	 */
4754 	svm_set_intercept_for_msr(vcpu, MSR_IA32_XSS, MSR_TYPE_RW,
4755 				  !guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) ||
4756 				  !guest_cpuid_has(vcpu, X86_FEATURE_XSAVES));
4757 }
4758 
4759 void sev_vcpu_after_set_cpuid(struct vcpu_svm *svm)
4760 {
4761 	struct kvm_vcpu *vcpu = &svm->vcpu;
4762 	struct kvm_cpuid_entry2 *best;
4763 
4764 	/* For sev guests, the memory encryption bit is not reserved in CR3.  */
4765 	best = kvm_find_cpuid_entry(vcpu, 0x8000001F);
4766 	if (best)
4767 		vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4768 }
4769 
4770 static void sev_es_init_vmcb(struct vcpu_svm *svm, bool init_event)
4771 {
4772 	struct kvm_sev_info *sev = to_kvm_sev_info(svm->vcpu.kvm);
4773 	struct vmcb *vmcb = svm->vmcb01.ptr;
4774 
4775 	svm->vmcb->control.misc_ctl |= SVM_MISC_ENABLE_SEV_ES;
4776 
4777 	/*
4778 	 * An SEV-ES guest requires a VMSA area that is a separate from the
4779 	 * VMCB page. Do not include the encryption mask on the VMSA physical
4780 	 * address since hardware will access it using the guest key.  Note,
4781 	 * the VMSA will be NULL if this vCPU is the destination for intrahost
4782 	 * migration, and will be copied later.
4783 	 */
4784 	if (!svm->sev_es.snp_has_guest_vmsa) {
4785 		if (svm->sev_es.vmsa)
4786 			svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa);
4787 		else
4788 			svm->vmcb->control.vmsa_pa = INVALID_PAGE;
4789 	}
4790 
4791 	if (cpu_feature_enabled(X86_FEATURE_ALLOWED_SEV_FEATURES))
4792 		svm->vmcb->control.allowed_sev_features = sev->vmsa_features |
4793 							  VMCB_ALLOWED_SEV_FEATURES_VALID;
4794 
4795 	/* Can't intercept CR register access, HV can't modify CR registers */
4796 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
4797 	svm_clr_intercept(svm, INTERCEPT_CR4_READ);
4798 	svm_clr_intercept(svm, INTERCEPT_CR8_READ);
4799 	svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
4800 	svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
4801 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
4802 
4803 	svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
4804 
4805 	/* Track EFER/CR register changes */
4806 	svm_set_intercept(svm, TRAP_EFER_WRITE);
4807 	svm_set_intercept(svm, TRAP_CR0_WRITE);
4808 	svm_set_intercept(svm, TRAP_CR4_WRITE);
4809 	svm_set_intercept(svm, TRAP_CR8_WRITE);
4810 
4811 	vmcb->control.intercepts[INTERCEPT_DR] = 0;
4812 	if (!sev_vcpu_has_debug_swap(svm)) {
4813 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
4814 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
4815 		svm_mark_intercepts_dirty(svm);
4816 	} else {
4817 		/*
4818 		 * Disable #DB intercept iff DebugSwap is enabled.  KVM doesn't
4819 		 * allow debugging SEV-ES guests, and enables DebugSwap iff
4820 		 * NO_NESTED_DATA_BP is supported, so there's no reason to
4821 		 * intercept #DB when DebugSwap is enabled.  For simplicity
4822 		 * with respect to guest debug, intercept #DB for other VMs
4823 		 * even if NO_NESTED_DATA_BP is supported, i.e. even if the
4824 		 * guest can't DoS the CPU with infinite #DB vectoring.
4825 		 */
4826 		clr_exception_intercept(svm, DB_VECTOR);
4827 	}
4828 
4829 	/* Can't intercept XSETBV, HV can't modify XCR0 directly */
4830 	svm_clr_intercept(svm, INTERCEPT_XSETBV);
4831 
4832 	/*
4833 	 * Set the GHCB MSR value as per the GHCB specification when emulating
4834 	 * vCPU RESET for an SEV-ES guest.
4835 	 */
4836 	if (!init_event)
4837 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version,
4838 						    GHCB_VERSION_MIN,
4839 						    sev_enc_bit));
4840 }
4841 
4842 void sev_init_vmcb(struct vcpu_svm *svm, bool init_event)
4843 {
4844 	struct kvm_vcpu *vcpu = &svm->vcpu;
4845 
4846 	svm->vmcb->control.misc_ctl |= SVM_MISC_ENABLE_SEV;
4847 	clr_exception_intercept(svm, UD_VECTOR);
4848 
4849 	/*
4850 	 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as
4851 	 * KVM can't decrypt guest memory to decode the faulting instruction.
4852 	 */
4853 	clr_exception_intercept(svm, GP_VECTOR);
4854 
4855 	if (init_event && is_sev_snp_guest(vcpu))
4856 		sev_snp_init_protected_guest_state(vcpu);
4857 
4858 	if (is_sev_es_guest(vcpu))
4859 		sev_es_init_vmcb(svm, init_event);
4860 }
4861 
4862 int sev_vcpu_create(struct kvm_vcpu *vcpu)
4863 {
4864 	struct vcpu_svm *svm = to_svm(vcpu);
4865 	struct page *vmsa_page;
4866 
4867 	mutex_init(&svm->sev_es.snp_vmsa_mutex);
4868 
4869 	if (!is_sev_es_guest(vcpu))
4870 		return 0;
4871 
4872 	/*
4873 	 * SEV-ES guests require a separate (from the VMCB) VMSA page used to
4874 	 * contain the encrypted register state of the guest.
4875 	 */
4876 	vmsa_page = snp_safe_alloc_page();
4877 	if (!vmsa_page)
4878 		return -ENOMEM;
4879 
4880 	svm->sev_es.vmsa = page_address(vmsa_page);
4881 	svm->sev_es.snp_pending_vmsa_gpa = INVALID_PAGE;
4882 	svm->sev_es.snp_guest_vmsa_gpa = INVALID_PAGE;
4883 
4884 	vcpu->arch.guest_tsc_protected = snp_is_secure_tsc_enabled(vcpu->kvm);
4885 
4886 	return 0;
4887 }
4888 
4889 void sev_es_prepare_switch_to_guest(struct vcpu_svm *svm, struct sev_es_save_area *hostsa)
4890 {
4891 	/*
4892 	 * All host state for SEV-ES guests is categorized into three swap types
4893 	 * based on how it is handled by hardware during a world switch:
4894 	 *
4895 	 * A: VMRUN:   Host state saved in host save area
4896 	 *    VMEXIT:  Host state loaded from host save area
4897 	 *
4898 	 * B: VMRUN:   Host state _NOT_ saved in host save area
4899 	 *    VMEXIT:  Host state loaded from host save area
4900 	 *
4901 	 * C: VMRUN:   Host state _NOT_ saved in host save area
4902 	 *    VMEXIT:  Host state initialized to default(reset) values
4903 	 *
4904 	 * Manually save type-B state, i.e. state that is loaded by VMEXIT but
4905 	 * isn't saved by VMRUN, that isn't already saved by VMSAVE (performed
4906 	 * by common SVM code).
4907 	 */
4908 	hostsa->xcr0 = kvm_host.xcr0;
4909 	hostsa->pkru = read_pkru();
4910 	hostsa->xss = kvm_host.xss;
4911 
4912 	/*
4913 	 * If DebugSwap is enabled, debug registers are loaded but NOT saved by
4914 	 * the CPU (Type-B). If DebugSwap is disabled/unsupported, the CPU does
4915 	 * not save or load debug registers.  Sadly, KVM can't prevent SNP
4916 	 * guests from lying about DebugSwap on secondary vCPUs, i.e. the
4917 	 * SEV_FEATURES provided at "AP Create" isn't guaranteed to match what
4918 	 * the guest has actually enabled (or not!) in the VMSA.
4919 	 *
4920 	 * If DebugSwap is *possible*, save the masks so that they're restored
4921 	 * if the guest enables DebugSwap.  But for the DRs themselves, do NOT
4922 	 * rely on the CPU to restore the host values; KVM will restore them as
4923 	 * needed in common code, via hw_breakpoint_restore().  Note, KVM does
4924 	 * NOT support virtualizing Breakpoint Extensions, i.e. the mask MSRs
4925 	 * don't need to be restored per se, KVM just needs to ensure they are
4926 	 * loaded with the correct values *if* the CPU writes the MSRs.
4927 	 */
4928 	if (sev_vcpu_has_debug_swap(svm) ||
4929 	    (cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) &&
4930 	     is_sev_snp_guest(&svm->vcpu))) {
4931 		hostsa->dr0_addr_mask = amd_get_dr_addr_mask(0);
4932 		hostsa->dr1_addr_mask = amd_get_dr_addr_mask(1);
4933 		hostsa->dr2_addr_mask = amd_get_dr_addr_mask(2);
4934 		hostsa->dr3_addr_mask = amd_get_dr_addr_mask(3);
4935 	}
4936 
4937 	/*
4938 	 * TSC_AUX is always virtualized for SEV-ES guests when the feature is
4939 	 * available, i.e. TSC_AUX is loaded on #VMEXIT from the host save area.
4940 	 * Set the save area to the current hardware value, i.e. the current
4941 	 * user return value, so that the correct value is restored on #VMEXIT.
4942 	 */
4943 	if (cpu_feature_enabled(X86_FEATURE_V_TSC_AUX) &&
4944 	    !WARN_ON_ONCE(tsc_aux_uret_slot < 0))
4945 		hostsa->tsc_aux = kvm_get_user_return_msr(tsc_aux_uret_slot);
4946 }
4947 
4948 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4949 {
4950 	struct vcpu_svm *svm = to_svm(vcpu);
4951 
4952 	/* First SIPI: Use the values as initially set by the VMM */
4953 	if (!svm->sev_es.received_first_sipi) {
4954 		svm->sev_es.received_first_sipi = true;
4955 		return;
4956 	}
4957 
4958 	/* Subsequent SIPI */
4959 	switch (svm->sev_es.ap_reset_hold_type) {
4960 	case AP_RESET_HOLD_NAE_EVENT:
4961 		/*
4962 		 * Return from an AP Reset Hold VMGEXIT, where the guest will
4963 		 * set the CS and RIP. Set SW_EXIT_INFO_2 to a non-zero value.
4964 		 */
4965 		svm_vmgexit_success(svm, 1);
4966 		break;
4967 	case AP_RESET_HOLD_MSR_PROTO:
4968 		/*
4969 		 * Return from an AP Reset Hold VMGEXIT, where the guest will
4970 		 * set the CS and RIP. Set GHCB data field to a non-zero value.
4971 		 */
4972 		set_ghcb_msr_bits(svm, 1,
4973 				  GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,
4974 				  GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
4975 
4976 		set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP,
4977 				  GHCB_MSR_INFO_MASK,
4978 				  GHCB_MSR_INFO_POS);
4979 		break;
4980 	default:
4981 		break;
4982 	}
4983 }
4984 
4985 struct page *snp_safe_alloc_page_node(int node, gfp_t gfp)
4986 {
4987 	unsigned long pfn;
4988 	struct page *p;
4989 
4990 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
4991 		return alloc_pages_node(node, gfp | __GFP_ZERO, 0);
4992 
4993 	/*
4994 	 * Allocate an SNP-safe page to workaround the SNP erratum where
4995 	 * the CPU will incorrectly signal an RMP violation #PF if a
4996 	 * hugepage (2MB or 1GB) collides with the RMP entry of a
4997 	 * 2MB-aligned VMCB, VMSA, or AVIC backing page.
4998 	 *
4999 	 * Allocate one extra page, choose a page which is not
5000 	 * 2MB-aligned, and free the other.
5001 	 */
5002 	p = alloc_pages_node(node, gfp | __GFP_ZERO, 1);
5003 	if (!p)
5004 		return NULL;
5005 
5006 	split_page(p, 1);
5007 
5008 	pfn = page_to_pfn(p);
5009 	if (IS_ALIGNED(pfn, PTRS_PER_PMD))
5010 		__free_page(p++);
5011 	else
5012 		__free_page(p + 1);
5013 
5014 	return p;
5015 }
5016 
5017 void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
5018 {
5019 	struct kvm_memory_slot *slot;
5020 	struct kvm *kvm = vcpu->kvm;
5021 	int order, rmp_level, ret;
5022 	struct page *page;
5023 	bool assigned;
5024 	kvm_pfn_t pfn;
5025 	gfn_t gfn;
5026 
5027 	gfn = gpa >> PAGE_SHIFT;
5028 
5029 	/*
5030 	 * The only time RMP faults occur for shared pages is when the guest is
5031 	 * triggering an RMP fault for an implicit page-state change from
5032 	 * shared->private. Implicit page-state changes are forwarded to
5033 	 * userspace via KVM_EXIT_MEMORY_FAULT events, however, so RMP faults
5034 	 * for shared pages should not end up here.
5035 	 */
5036 	if (!kvm_mem_is_private(kvm, gfn)) {
5037 		pr_warn_ratelimited("SEV: Unexpected RMP fault for non-private GPA 0x%llx\n",
5038 				    gpa);
5039 		return;
5040 	}
5041 
5042 	slot = gfn_to_memslot(kvm, gfn);
5043 	if (!kvm_slot_has_gmem(slot)) {
5044 		pr_warn_ratelimited("SEV: Unexpected RMP fault, non-private slot for GPA 0x%llx\n",
5045 				    gpa);
5046 		return;
5047 	}
5048 
5049 	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order);
5050 	if (ret) {
5051 		pr_warn_ratelimited("SEV: Unexpected RMP fault, no backing page for private GPA 0x%llx\n",
5052 				    gpa);
5053 		return;
5054 	}
5055 
5056 	ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
5057 	if (ret || !assigned) {
5058 		pr_warn_ratelimited("SEV: Unexpected RMP fault, no assigned RMP entry found for GPA 0x%llx PFN 0x%llx error %d\n",
5059 				    gpa, pfn, ret);
5060 		goto out_no_trace;
5061 	}
5062 
5063 	/*
5064 	 * There are 2 cases where a PSMASH may be needed to resolve an #NPF
5065 	 * with PFERR_GUEST_RMP_BIT set:
5066 	 *
5067 	 * 1) RMPADJUST/PVALIDATE can trigger an #NPF with PFERR_GUEST_SIZEM
5068 	 *    bit set if the guest issues them with a smaller granularity than
5069 	 *    what is indicated by the page-size bit in the 2MB RMP entry for
5070 	 *    the PFN that backs the GPA.
5071 	 *
5072 	 * 2) Guest access via NPT can trigger an #NPF if the NPT mapping is
5073 	 *    smaller than what is indicated by the 2MB RMP entry for the PFN
5074 	 *    that backs the GPA.
5075 	 *
5076 	 * In both these cases, the corresponding 2M RMP entry needs to
5077 	 * be PSMASH'd to 512 4K RMP entries.  If the RMP entry is already
5078 	 * split into 4K RMP entries, then this is likely a spurious case which
5079 	 * can occur when there are concurrent accesses by the guest to a 2MB
5080 	 * GPA range that is backed by a 2MB-aligned PFN who's RMP entry is in
5081 	 * the process of being PMASH'd into 4K entries. These cases should
5082 	 * resolve automatically on subsequent accesses, so just ignore them
5083 	 * here.
5084 	 */
5085 	if (rmp_level == PG_LEVEL_4K)
5086 		goto out;
5087 
5088 	ret = snp_rmptable_psmash(pfn);
5089 	if (ret) {
5090 		/*
5091 		 * Look it up again. If it's 4K now then the PSMASH may have
5092 		 * raced with another process and the issue has already resolved
5093 		 * itself.
5094 		 */
5095 		if (!snp_lookup_rmpentry(pfn, &assigned, &rmp_level) &&
5096 		    assigned && rmp_level == PG_LEVEL_4K)
5097 			goto out;
5098 
5099 		pr_warn_ratelimited("SEV: Unable to split RMP entry for GPA 0x%llx PFN 0x%llx ret %d\n",
5100 				    gpa, pfn, ret);
5101 	}
5102 
5103 	kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD);
5104 out:
5105 	trace_kvm_rmp_fault(vcpu, gpa, pfn, error_code, rmp_level, ret);
5106 out_no_trace:
5107 	kvm_release_page_unused(page);
5108 }
5109 
5110 static bool is_pfn_range_shared(kvm_pfn_t start, kvm_pfn_t end)
5111 {
5112 	kvm_pfn_t pfn = start;
5113 
5114 	while (pfn < end) {
5115 		int ret, rmp_level;
5116 		bool assigned;
5117 
5118 		ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
5119 		if (ret) {
5120 			pr_warn_ratelimited("SEV: Failed to retrieve RMP entry: PFN 0x%llx GFN start 0x%llx GFN end 0x%llx RMP level %d error %d\n",
5121 					    pfn, start, end, rmp_level, ret);
5122 			return false;
5123 		}
5124 
5125 		if (assigned) {
5126 			pr_debug("%s: overlap detected, PFN 0x%llx start 0x%llx end 0x%llx RMP level %d\n",
5127 				 __func__, pfn, start, end, rmp_level);
5128 			return false;
5129 		}
5130 
5131 		pfn++;
5132 	}
5133 
5134 	return true;
5135 }
5136 
5137 static bool is_large_rmp_possible(kvm_pfn_t pfn, kvm_pfn_t nr_pages)
5138 {
5139 	kvm_pfn_t pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD);
5140 
5141 	/*
5142 	 * If this is a large folio, and the entire 2M range containing the
5143 	 * PFN is currently shared, then the entire 2M-aligned range can be
5144 	 * set to private via a single 2M RMP entry.
5145 	 */
5146 	if (nr_pages >= KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) &&
5147 	    is_pfn_range_shared(pfn_aligned, pfn_aligned + PTRS_PER_PMD))
5148 		return true;
5149 
5150 	return false;
5151 }
5152 
5153 int sev_gmem_make_private(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, kvm_pfn_t nr_pages)
5154 {
5155 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
5156 	kvm_pfn_t pfn_aligned;
5157 	gfn_t gfn_aligned;
5158 	int level, rc;
5159 	bool assigned;
5160 
5161 	if (!sev_snp_guest(kvm))
5162 		return 0;
5163 
5164 	if (WARN_ON_ONCE(nr_pages != 1))
5165 		return -EIO;
5166 
5167 	rc = snp_lookup_rmpentry(pfn, &assigned, &level);
5168 	if (rc) {
5169 		pr_err_ratelimited("SEV: Failed to look up RMP entry: GFN %llx PFN %llx error %d\n",
5170 				   gfn, pfn, rc);
5171 		return -ENOENT;
5172 	}
5173 
5174 	if (assigned) {
5175 		pr_debug("%s: already assigned: gfn %llx pfn %llx nr_pages %llx level %d\n",
5176 			 __func__, gfn, pfn, nr_pages, level);
5177 		return 0;
5178 	}
5179 
5180 	if (is_large_rmp_possible(pfn, nr_pages)) {
5181 		level = PG_LEVEL_2M;
5182 		pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD);
5183 		gfn_aligned = ALIGN_DOWN(gfn, PTRS_PER_PMD);
5184 	} else {
5185 		level = PG_LEVEL_4K;
5186 		pfn_aligned = pfn;
5187 		gfn_aligned = gfn;
5188 	}
5189 
5190 	rc = rmp_make_private(pfn_aligned, gfn_to_gpa(gfn_aligned), level, sev->asid, false);
5191 	if (rc) {
5192 		pr_err_ratelimited("SEV: Failed to update RMP entry: GFN %llx PFN %llx level %d error %d\n",
5193 				   gfn, pfn, level, rc);
5194 		return -EINVAL;
5195 	}
5196 
5197 	pr_debug("%s: updated: gfn %llx pfn %llx pfn_aligned %llx nr_pages %llx level %d\n",
5198 		 __func__, gfn, pfn, pfn_aligned, nr_pages, level);
5199 
5200 	return 0;
5201 }
5202 
5203 void sev_gmem_make_shared(kvm_pfn_t pfn, kvm_pfn_t nr_pages)
5204 {
5205 	kvm_pfn_t end = pfn + nr_pages;
5206 
5207 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
5208 		return;
5209 
5210 	pr_debug("%s: PFN start 0x%llx PFN end 0x%llx\n", __func__, pfn, end);
5211 
5212 	while (pfn < end) {
5213 		bool use_2m_update = false;
5214 		int rc, rmp_level;
5215 		bool assigned;
5216 
5217 		rc = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
5218 		if (rc || !assigned)
5219 			goto next_pfn;
5220 
5221 		use_2m_update = IS_ALIGNED(pfn, PTRS_PER_PMD) &&
5222 				end >= (pfn + PTRS_PER_PMD) &&
5223 				rmp_level > PG_LEVEL_4K;
5224 
5225 		/*
5226 		 * If an unaligned PFN corresponds to a 2M region assigned as a
5227 		 * large page in the RMP table, PSMASH the region into individual
5228 		 * 4K RMP entries before attempting to convert a 4K sub-page.
5229 		 */
5230 		if (!use_2m_update && rmp_level > PG_LEVEL_4K) {
5231 			/*
5232 			 * This shouldn't fail, but if it does, report it, but
5233 			 * still try to update RMP entry to shared and pray this
5234 			 * was a spurious error that can be addressed later.
5235 			 */
5236 			rc = snp_rmptable_psmash(pfn);
5237 			WARN_ONCE(rc, "SEV: Failed to PSMASH RMP entry for PFN 0x%llx error %d\n",
5238 				  pfn, rc);
5239 		}
5240 
5241 		rc = rmp_make_shared(pfn, use_2m_update ? PG_LEVEL_2M : PG_LEVEL_4K);
5242 		if (WARN_ONCE(rc, "SEV: Failed to update RMP entry for PFN 0x%llx error %d\n",
5243 			      pfn, rc))
5244 			goto next_pfn;
5245 
5246 		/*
5247 		 * SEV-ES avoids host/guest cache coherency issues through
5248 		 * WBNOINVD hooks issued via MMU notifiers during run-time, and
5249 		 * KVM's VM destroy path at shutdown. Those MMU notifier events
5250 		 * don't cover gmem since there is no requirement to map pages
5251 		 * to a HVA in order to use them for a running guest. While the
5252 		 * shutdown path would still likely cover things for SNP guests,
5253 		 * userspace may also free gmem pages during run-time via
5254 		 * hole-punching operations on the guest_memfd, so flush the
5255 		 * cache entries for these pages before free'ing them back to
5256 		 * the host.
5257 		 */
5258 		clflush_cache_range(__va(pfn_to_hpa(pfn)),
5259 				    use_2m_update ? PMD_SIZE : PAGE_SIZE);
5260 next_pfn:
5261 		pfn += use_2m_update ? PTRS_PER_PMD : 1;
5262 		cond_resched();
5263 	}
5264 }
5265 
5266 void sev_gmem_invalidate_range(struct kvm *kvm, struct kvm_gfn_range *range)
5267 {
5268 	struct kvm_vcpu *vcpu;
5269 	unsigned long i;
5270 
5271 	lockdep_assert_held_write(&kvm->mmu_lock);
5272 
5273 	/*
5274 	 * An unstable result for "is SNP" is a-ok here, thanks to mmu_lock.
5275 	 * The vCPU's VMSA GPA is invalidated before the vCPU is made visible
5276 	 * to other tasks, and can only become valid while holding mmu_lock,
5277 	 * after the VM is fully committed to being an SNP VM.
5278 	 */
5279 	if (!____sev_snp_guest(kvm))
5280 		return;
5281 
5282 	kvm_for_each_vcpu(i, vcpu, kvm) {
5283 		/*
5284 		 * Read snp_guest_vmsa_gpa without taking the vCPU's VMSA mutex
5285 		 * (or its generic mutex) as mmu_lock is held, i.e. this task
5286 		 * can't sleep.  The VMSA is invalidated outside of mmu_lock,
5287 		 * but can only become valid inside of mmu_lock, i.e. the below
5288 		 * can get false positives, but not false negatives.  A false
5289 		 * positive is benign, as a spurious request simply forces the
5290 		 * vCPU to re-establish its VMSA.
5291 		 */
5292 		gpa_t gpa = READ_ONCE(to_svm(vcpu)->sev_es.snp_guest_vmsa_gpa);
5293 
5294 		if (VALID_PAGE(gpa) &&
5295 		    gpa_to_gfn(gpa) >= range->start &&
5296 		    gpa_to_gfn(gpa) < range->end)
5297 			kvm_make_request_and_kick(KVM_REQ_VMSA_PAGE_RELOAD, vcpu);
5298 	}
5299 }
5300 
5301 int sev_gmem_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn, bool is_private)
5302 {
5303 	int level, rc;
5304 	bool assigned;
5305 
5306 	if (!sev_snp_guest(kvm))
5307 		return 0;
5308 
5309 	rc = snp_lookup_rmpentry(pfn, &assigned, &level);
5310 	if (rc || !assigned)
5311 		return PG_LEVEL_4K;
5312 
5313 	return level;
5314 }
5315 
5316 struct vmcb_save_area *sev_decrypt_vmsa(struct kvm_vcpu *vcpu)
5317 {
5318 	struct vcpu_svm *svm = to_svm(vcpu);
5319 	struct vmcb_save_area *vmsa;
5320 	struct kvm_sev_info *sev;
5321 	int error = 0;
5322 	int ret;
5323 
5324 	if (!is_sev_es_guest(vcpu))
5325 		return NULL;
5326 
5327 	/*
5328 	 * If the VMSA has not yet been encrypted, return a pointer to the
5329 	 * current un-encrypted VMSA.
5330 	 */
5331 	if (!vcpu->arch.guest_state_protected)
5332 		return (struct vmcb_save_area *)svm->sev_es.vmsa;
5333 
5334 	sev = to_kvm_sev_info(vcpu->kvm);
5335 
5336 	/* Check if the SEV policy allows debugging */
5337 	if (is_sev_snp_guest(vcpu)) {
5338 		if (!(sev->policy & SNP_POLICY_MASK_DEBUG))
5339 			return NULL;
5340 	} else {
5341 		if (sev->policy & SEV_POLICY_MASK_NODBG)
5342 			return NULL;
5343 	}
5344 
5345 	if (is_sev_snp_guest(vcpu)) {
5346 		struct sev_data_snp_dbg dbg = {0};
5347 
5348 		vmsa = snp_alloc_firmware_page(__GFP_ZERO);
5349 		if (!vmsa)
5350 			return NULL;
5351 
5352 		dbg.gctx_paddr = __psp_pa(sev->snp_context);
5353 		dbg.src_addr = svm->vmcb->control.vmsa_pa;
5354 		dbg.dst_addr = __psp_pa(vmsa);
5355 
5356 		ret = sev_do_cmd(SEV_CMD_SNP_DBG_DECRYPT, &dbg, &error);
5357 
5358 		/*
5359 		 * Return the target page to a hypervisor page no matter what.
5360 		 * If this fails, the page can't be used, so leak it and don't
5361 		 * try to use it.
5362 		 */
5363 		if (snp_page_reclaim(vcpu->kvm, PHYS_PFN(__pa(vmsa))))
5364 			return NULL;
5365 
5366 		if (ret) {
5367 			pr_err("SEV: SNP_DBG_DECRYPT failed ret=%d, fw_error=%d (%#x)\n",
5368 			       ret, error, error);
5369 			free_page((unsigned long)vmsa);
5370 
5371 			return NULL;
5372 		}
5373 	} else {
5374 		struct sev_data_dbg dbg = {0};
5375 		struct page *vmsa_page;
5376 
5377 		vmsa_page = alloc_page(GFP_KERNEL);
5378 		if (!vmsa_page)
5379 			return NULL;
5380 
5381 		vmsa = page_address(vmsa_page);
5382 
5383 		dbg.handle = sev->handle;
5384 		dbg.src_addr = svm->vmcb->control.vmsa_pa;
5385 		dbg.dst_addr = __psp_pa(vmsa);
5386 		dbg.len = PAGE_SIZE;
5387 
5388 		ret = sev_do_cmd(SEV_CMD_DBG_DECRYPT, &dbg, &error);
5389 		if (ret) {
5390 			pr_err("SEV: SEV_CMD_DBG_DECRYPT failed ret=%d, fw_error=%d (0x%x)\n",
5391 			       ret, error, error);
5392 			__free_page(vmsa_page);
5393 
5394 			return NULL;
5395 		}
5396 	}
5397 
5398 	return vmsa;
5399 }
5400 
5401 void sev_free_decrypted_vmsa(struct kvm_vcpu *vcpu, struct vmcb_save_area *vmsa)
5402 {
5403 	/* If the VMSA has not yet been encrypted, nothing was allocated */
5404 	if (!vcpu->arch.guest_state_protected || !vmsa)
5405 		return;
5406 
5407 	free_page((unsigned long)vmsa);
5408 }
5409