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