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