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