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