xref: /linux/arch/x86/kvm/svm/sev.c (revision b74710eaff314d6afe4fb0bbe9bc7657bf226fd4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM-SEV support
6  *
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/kvm_types.h>
12 #include <linux/kvm_host.h>
13 #include <linux/kernel.h>
14 #include <linux/highmem.h>
15 #include <linux/psp.h>
16 #include <linux/psp-sev.h>
17 #include <linux/pagemap.h>
18 #include <linux/swap.h>
19 #include <linux/misc_cgroup.h>
20 #include <linux/processor.h>
21 #include <linux/trace_events.h>
22 #include <uapi/linux/sev-guest.h>
23 
24 #include <asm/pkru.h>
25 #include <asm/trapnr.h>
26 #include <asm/fpu/xcr.h>
27 #include <asm/fpu/xstate.h>
28 #include <asm/debugreg.h>
29 #include <asm/msr.h>
30 #include <asm/sev.h>
31 
32 #include "mmu.h"
33 #include "x86.h"
34 #include "svm.h"
35 #include "svm_ops.h"
36 #include "cpuid.h"
37 #include "trace.h"
38 
39 #define GHCB_VERSION_MAX	2ULL
40 #define GHCB_VERSION_DEFAULT	2ULL
41 #define GHCB_VERSION_MIN	1ULL
42 
43 #define GHCB_HV_FT_SUPPORTED	(GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)
44 
45 /* enable/disable SEV support */
46 static bool sev_enabled = true;
47 module_param_named(sev, sev_enabled, bool, 0444);
48 
49 /* enable/disable SEV-ES support */
50 static bool sev_es_enabled = true;
51 module_param_named(sev_es, sev_es_enabled, bool, 0444);
52 
53 /* enable/disable SEV-SNP support */
54 static bool sev_snp_enabled = true;
55 module_param_named(sev_snp, sev_snp_enabled, bool, 0444);
56 
57 /* enable/disable SEV-ES DebugSwap support */
58 static bool sev_es_debug_swap_enabled = true;
59 module_param_named(debug_swap, sev_es_debug_swap_enabled, bool, 0444);
60 static u64 sev_supported_vmsa_features;
61 
62 #define AP_RESET_HOLD_NONE		0
63 #define AP_RESET_HOLD_NAE_EVENT		1
64 #define AP_RESET_HOLD_MSR_PROTO		2
65 
66 /* As defined by SEV-SNP Firmware ABI, under "Guest Policy". */
67 #define SNP_POLICY_MASK_API_MINOR	GENMASK_ULL(7, 0)
68 #define SNP_POLICY_MASK_API_MAJOR	GENMASK_ULL(15, 8)
69 #define SNP_POLICY_MASK_SMT		BIT_ULL(16)
70 #define SNP_POLICY_MASK_RSVD_MBO	BIT_ULL(17)
71 #define SNP_POLICY_MASK_DEBUG		BIT_ULL(19)
72 #define SNP_POLICY_MASK_SINGLE_SOCKET	BIT_ULL(20)
73 
74 #define SNP_POLICY_MASK_VALID		(SNP_POLICY_MASK_API_MINOR	| \
75 					 SNP_POLICY_MASK_API_MAJOR	| \
76 					 SNP_POLICY_MASK_SMT		| \
77 					 SNP_POLICY_MASK_RSVD_MBO	| \
78 					 SNP_POLICY_MASK_DEBUG		| \
79 					 SNP_POLICY_MASK_SINGLE_SOCKET)
80 
81 #define INITIAL_VMSA_GPA 0xFFFFFFFFF000
82 
83 static u8 sev_enc_bit;
84 static DECLARE_RWSEM(sev_deactivate_lock);
85 static DEFINE_MUTEX(sev_bitmap_lock);
86 unsigned int max_sev_asid;
87 static unsigned int min_sev_asid;
88 static unsigned long sev_me_mask;
89 static unsigned int nr_asids;
90 static unsigned long *sev_asid_bitmap;
91 static unsigned long *sev_reclaim_asid_bitmap;
92 
93 static int snp_decommission_context(struct kvm *kvm);
94 
95 struct enc_region {
96 	struct list_head list;
97 	unsigned long npages;
98 	struct page **pages;
99 	unsigned long uaddr;
100 	unsigned long size;
101 };
102 
103 /* Called with the sev_bitmap_lock held, or on shutdown  */
104 static int sev_flush_asids(unsigned int min_asid, unsigned int max_asid)
105 {
106 	int ret, error = 0;
107 	unsigned int asid;
108 
109 	/* Check if there are any ASIDs to reclaim before performing a flush */
110 	asid = find_next_bit(sev_reclaim_asid_bitmap, nr_asids, min_asid);
111 	if (asid > max_asid)
112 		return -EBUSY;
113 
114 	/*
115 	 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
116 	 * so it must be guarded.
117 	 */
118 	down_write(&sev_deactivate_lock);
119 
120 	wbinvd_on_all_cpus();
121 
122 	if (sev_snp_enabled)
123 		ret = sev_do_cmd(SEV_CMD_SNP_DF_FLUSH, NULL, &error);
124 	else
125 		ret = sev_guest_df_flush(&error);
126 
127 	up_write(&sev_deactivate_lock);
128 
129 	if (ret)
130 		pr_err("SEV%s: DF_FLUSH failed, ret=%d, error=%#x\n",
131 		       sev_snp_enabled ? "-SNP" : "", ret, error);
132 
133 	return ret;
134 }
135 
136 static inline bool is_mirroring_enc_context(struct kvm *kvm)
137 {
138 	return !!to_kvm_sev_info(kvm)->enc_context_owner;
139 }
140 
141 static bool sev_vcpu_has_debug_swap(struct vcpu_svm *svm)
142 {
143 	struct kvm_vcpu *vcpu = &svm->vcpu;
144 	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
145 
146 	return sev->vmsa_features & SVM_SEV_FEAT_DEBUG_SWAP;
147 }
148 
149 /* Must be called with the sev_bitmap_lock held */
150 static bool __sev_recycle_asids(unsigned int min_asid, unsigned int max_asid)
151 {
152 	if (sev_flush_asids(min_asid, max_asid))
153 		return false;
154 
155 	/* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */
156 	bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
157 		   nr_asids);
158 	bitmap_zero(sev_reclaim_asid_bitmap, nr_asids);
159 
160 	return true;
161 }
162 
163 static int sev_misc_cg_try_charge(struct kvm_sev_info *sev)
164 {
165 	enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
166 	return misc_cg_try_charge(type, sev->misc_cg, 1);
167 }
168 
169 static void sev_misc_cg_uncharge(struct kvm_sev_info *sev)
170 {
171 	enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
172 	misc_cg_uncharge(type, sev->misc_cg, 1);
173 }
174 
175 static int sev_asid_new(struct kvm_sev_info *sev)
176 {
177 	/*
178 	 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid.
179 	 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1.
180 	 * Note: min ASID can end up larger than the max if basic SEV support is
181 	 * effectively disabled by disallowing use of ASIDs for SEV guests.
182 	 */
183 	unsigned int min_asid = sev->es_active ? 1 : min_sev_asid;
184 	unsigned int max_asid = sev->es_active ? min_sev_asid - 1 : max_sev_asid;
185 	unsigned int asid;
186 	bool retry = true;
187 	int ret;
188 
189 	if (min_asid > max_asid)
190 		return -ENOTTY;
191 
192 	WARN_ON(sev->misc_cg);
193 	sev->misc_cg = get_current_misc_cg();
194 	ret = sev_misc_cg_try_charge(sev);
195 	if (ret) {
196 		put_misc_cg(sev->misc_cg);
197 		sev->misc_cg = NULL;
198 		return ret;
199 	}
200 
201 	mutex_lock(&sev_bitmap_lock);
202 
203 again:
204 	asid = find_next_zero_bit(sev_asid_bitmap, max_asid + 1, min_asid);
205 	if (asid > max_asid) {
206 		if (retry && __sev_recycle_asids(min_asid, max_asid)) {
207 			retry = false;
208 			goto again;
209 		}
210 		mutex_unlock(&sev_bitmap_lock);
211 		ret = -EBUSY;
212 		goto e_uncharge;
213 	}
214 
215 	__set_bit(asid, sev_asid_bitmap);
216 
217 	mutex_unlock(&sev_bitmap_lock);
218 
219 	sev->asid = asid;
220 	return 0;
221 e_uncharge:
222 	sev_misc_cg_uncharge(sev);
223 	put_misc_cg(sev->misc_cg);
224 	sev->misc_cg = NULL;
225 	return ret;
226 }
227 
228 static unsigned int sev_get_asid(struct kvm *kvm)
229 {
230 	return to_kvm_sev_info(kvm)->asid;
231 }
232 
233 static void sev_asid_free(struct kvm_sev_info *sev)
234 {
235 	struct svm_cpu_data *sd;
236 	int cpu;
237 
238 	mutex_lock(&sev_bitmap_lock);
239 
240 	__set_bit(sev->asid, sev_reclaim_asid_bitmap);
241 
242 	for_each_possible_cpu(cpu) {
243 		sd = per_cpu_ptr(&svm_data, cpu);
244 		sd->sev_vmcbs[sev->asid] = NULL;
245 	}
246 
247 	mutex_unlock(&sev_bitmap_lock);
248 
249 	sev_misc_cg_uncharge(sev);
250 	put_misc_cg(sev->misc_cg);
251 	sev->misc_cg = NULL;
252 }
253 
254 static void sev_decommission(unsigned int handle)
255 {
256 	struct sev_data_decommission decommission;
257 
258 	if (!handle)
259 		return;
260 
261 	decommission.handle = handle;
262 	sev_guest_decommission(&decommission, NULL);
263 }
264 
265 /*
266  * Transition a page to hypervisor-owned/shared state in the RMP table. This
267  * should not fail under normal conditions, but leak the page should that
268  * happen since it will no longer be usable by the host due to RMP protections.
269  */
270 static int kvm_rmp_make_shared(struct kvm *kvm, u64 pfn, enum pg_level level)
271 {
272 	if (KVM_BUG_ON(rmp_make_shared(pfn, level), kvm)) {
273 		snp_leak_pages(pfn, page_level_size(level) >> PAGE_SHIFT);
274 		return -EIO;
275 	}
276 
277 	return 0;
278 }
279 
280 /*
281  * Certain page-states, such as Pre-Guest and Firmware pages (as documented
282  * in Chapter 5 of the SEV-SNP Firmware ABI under "Page States") cannot be
283  * directly transitioned back to normal/hypervisor-owned state via RMPUPDATE
284  * unless they are reclaimed first.
285  *
286  * Until they are reclaimed and subsequently transitioned via RMPUPDATE, they
287  * might not be usable by the host due to being set as immutable or still
288  * being associated with a guest ASID.
289  *
290  * Bug the VM and leak the page if reclaim fails, or if the RMP entry can't be
291  * converted back to shared, as the page is no longer usable due to RMP
292  * protections, and it's infeasible for the guest to continue on.
293  */
294 static int snp_page_reclaim(struct kvm *kvm, u64 pfn)
295 {
296 	struct sev_data_snp_page_reclaim data = {0};
297 	int fw_err, rc;
298 
299 	data.paddr = __sme_set(pfn << PAGE_SHIFT);
300 	rc = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &fw_err);
301 	if (KVM_BUG(rc, kvm, "Failed to reclaim PFN %llx, rc %d fw_err %d", pfn, rc, fw_err)) {
302 		snp_leak_pages(pfn, 1);
303 		return -EIO;
304 	}
305 
306 	if (kvm_rmp_make_shared(kvm, pfn, PG_LEVEL_4K))
307 		return -EIO;
308 
309 	return rc;
310 }
311 
312 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
313 {
314 	struct sev_data_deactivate deactivate;
315 
316 	if (!handle)
317 		return;
318 
319 	deactivate.handle = handle;
320 
321 	/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
322 	down_read(&sev_deactivate_lock);
323 	sev_guest_deactivate(&deactivate, NULL);
324 	up_read(&sev_deactivate_lock);
325 
326 	sev_decommission(handle);
327 }
328 
329 /*
330  * This sets up bounce buffers/firmware pages to handle SNP Guest Request
331  * messages (e.g. attestation requests). See "SNP Guest Request" in the GHCB
332  * 2.0 specification for more details.
333  *
334  * Technically, when an SNP Guest Request is issued, the guest will provide its
335  * own request/response pages, which could in theory be passed along directly
336  * to firmware rather than using bounce pages. However, these pages would need
337  * special care:
338  *
339  *   - Both pages are from shared guest memory, so they need to be protected
340  *     from migration/etc. occurring while firmware reads/writes to them. At a
341  *     minimum, this requires elevating the ref counts and potentially needing
342  *     an explicit pinning of the memory. This places additional restrictions
343  *     on what type of memory backends userspace can use for shared guest
344  *     memory since there is some reliance on using refcounted pages.
345  *
346  *   - The response page needs to be switched to Firmware-owned[1] state
347  *     before the firmware can write to it, which can lead to potential
348  *     host RMP #PFs if the guest is misbehaved and hands the host a
349  *     guest page that KVM might write to for other reasons (e.g. virtio
350  *     buffers/etc.).
351  *
352  * Both of these issues can be avoided completely by using separately-allocated
353  * bounce pages for both the request/response pages and passing those to
354  * firmware instead. So that's what is being set up here.
355  *
356  * Guest requests rely on message sequence numbers to ensure requests are
357  * issued to firmware in the order the guest issues them, so concurrent guest
358  * requests generally shouldn't happen. But a misbehaved guest could issue
359  * concurrent guest requests in theory, so a mutex is used to serialize
360  * access to the bounce buffers.
361  *
362  * [1] See the "Page States" section of the SEV-SNP Firmware ABI for more
363  *     details on Firmware-owned pages, along with "RMP and VMPL Access Checks"
364  *     in the APM for details on the related RMP restrictions.
365  */
366 static int snp_guest_req_init(struct kvm *kvm)
367 {
368 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
369 	struct page *req_page;
370 
371 	req_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
372 	if (!req_page)
373 		return -ENOMEM;
374 
375 	sev->guest_resp_buf = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
376 	if (!sev->guest_resp_buf) {
377 		__free_page(req_page);
378 		return -EIO;
379 	}
380 
381 	sev->guest_req_buf = page_address(req_page);
382 	mutex_init(&sev->guest_req_mutex);
383 
384 	return 0;
385 }
386 
387 static void snp_guest_req_cleanup(struct kvm *kvm)
388 {
389 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
390 
391 	if (sev->guest_resp_buf)
392 		snp_free_firmware_page(sev->guest_resp_buf);
393 
394 	if (sev->guest_req_buf)
395 		__free_page(virt_to_page(sev->guest_req_buf));
396 
397 	sev->guest_req_buf = NULL;
398 	sev->guest_resp_buf = NULL;
399 }
400 
401 static int __sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp,
402 			    struct kvm_sev_init *data,
403 			    unsigned long vm_type)
404 {
405 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
406 	struct sev_platform_init_args init_args = {0};
407 	bool es_active = vm_type != KVM_X86_SEV_VM;
408 	u64 valid_vmsa_features = es_active ? sev_supported_vmsa_features : 0;
409 	int ret;
410 
411 	if (kvm->created_vcpus)
412 		return -EINVAL;
413 
414 	if (data->flags)
415 		return -EINVAL;
416 
417 	if (data->vmsa_features & ~valid_vmsa_features)
418 		return -EINVAL;
419 
420 	if (data->ghcb_version > GHCB_VERSION_MAX || (!es_active && data->ghcb_version))
421 		return -EINVAL;
422 
423 	if (unlikely(sev->active))
424 		return -EINVAL;
425 
426 	sev->active = true;
427 	sev->es_active = es_active;
428 	sev->vmsa_features = data->vmsa_features;
429 	sev->ghcb_version = data->ghcb_version;
430 
431 	/*
432 	 * Currently KVM supports the full range of mandatory features defined
433 	 * by version 2 of the GHCB protocol, so default to that for SEV-ES
434 	 * guests created via KVM_SEV_INIT2.
435 	 */
436 	if (sev->es_active && !sev->ghcb_version)
437 		sev->ghcb_version = GHCB_VERSION_DEFAULT;
438 
439 	if (vm_type == KVM_X86_SNP_VM)
440 		sev->vmsa_features |= SVM_SEV_FEAT_SNP_ACTIVE;
441 
442 	ret = sev_asid_new(sev);
443 	if (ret)
444 		goto e_no_asid;
445 
446 	init_args.probe = false;
447 	ret = sev_platform_init(&init_args);
448 	if (ret)
449 		goto e_free;
450 
451 	/* This needs to happen after SEV/SNP firmware initialization. */
452 	if (vm_type == KVM_X86_SNP_VM) {
453 		ret = snp_guest_req_init(kvm);
454 		if (ret)
455 			goto e_free;
456 	}
457 
458 	INIT_LIST_HEAD(&sev->regions_list);
459 	INIT_LIST_HEAD(&sev->mirror_vms);
460 	sev->need_init = false;
461 
462 	kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_SEV);
463 
464 	return 0;
465 
466 e_free:
467 	argp->error = init_args.error;
468 	sev_asid_free(sev);
469 	sev->asid = 0;
470 e_no_asid:
471 	sev->vmsa_features = 0;
472 	sev->es_active = false;
473 	sev->active = false;
474 	return ret;
475 }
476 
477 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
478 {
479 	struct kvm_sev_init data = {
480 		.vmsa_features = 0,
481 		.ghcb_version = 0,
482 	};
483 	unsigned long vm_type;
484 
485 	if (kvm->arch.vm_type != KVM_X86_DEFAULT_VM)
486 		return -EINVAL;
487 
488 	vm_type = (argp->id == KVM_SEV_INIT ? KVM_X86_SEV_VM : KVM_X86_SEV_ES_VM);
489 
490 	/*
491 	 * KVM_SEV_ES_INIT has been deprecated by KVM_SEV_INIT2, so it will
492 	 * continue to only ever support the minimal GHCB protocol version.
493 	 */
494 	if (vm_type == KVM_X86_SEV_ES_VM)
495 		data.ghcb_version = GHCB_VERSION_MIN;
496 
497 	return __sev_guest_init(kvm, argp, &data, vm_type);
498 }
499 
500 static int sev_guest_init2(struct kvm *kvm, struct kvm_sev_cmd *argp)
501 {
502 	struct kvm_sev_init data;
503 
504 	if (!to_kvm_sev_info(kvm)->need_init)
505 		return -EINVAL;
506 
507 	if (kvm->arch.vm_type != KVM_X86_SEV_VM &&
508 	    kvm->arch.vm_type != KVM_X86_SEV_ES_VM &&
509 	    kvm->arch.vm_type != KVM_X86_SNP_VM)
510 		return -EINVAL;
511 
512 	if (copy_from_user(&data, u64_to_user_ptr(argp->data), sizeof(data)))
513 		return -EFAULT;
514 
515 	return __sev_guest_init(kvm, argp, &data, kvm->arch.vm_type);
516 }
517 
518 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
519 {
520 	unsigned int asid = sev_get_asid(kvm);
521 	struct sev_data_activate activate;
522 	int ret;
523 
524 	/* activate ASID on the given handle */
525 	activate.handle = handle;
526 	activate.asid   = asid;
527 	ret = sev_guest_activate(&activate, error);
528 
529 	return ret;
530 }
531 
532 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
533 {
534 	CLASS(fd, f)(fd);
535 
536 	if (fd_empty(f))
537 		return -EBADF;
538 
539 	return sev_issue_cmd_external_user(fd_file(f), id, data, error);
540 }
541 
542 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
543 {
544 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
545 
546 	return __sev_issue_cmd(sev->fd, id, data, error);
547 }
548 
549 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
550 {
551 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
552 	struct sev_data_launch_start start;
553 	struct kvm_sev_launch_start params;
554 	void *dh_blob, *session_blob;
555 	int *error = &argp->error;
556 	int ret;
557 
558 	if (!sev_guest(kvm))
559 		return -ENOTTY;
560 
561 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
562 		return -EFAULT;
563 
564 	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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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
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 
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
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 (!sev_es_guest(src))
1975 		return 0;
1976 
1977 	if (atomic_read(&src->online_vcpus) != atomic_read(&dst->online_vcpus))
1978 		return -EINVAL;
1979 
1980 	kvm_for_each_vcpu(i, src_vcpu, src) {
1981 		if (!src_vcpu->arch.guest_state_protected)
1982 			return -EINVAL;
1983 	}
1984 
1985 	return 0;
1986 }
1987 
1988 int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
1989 {
1990 	struct kvm_sev_info *dst_sev = to_kvm_sev_info(kvm);
1991 	struct kvm_sev_info *src_sev, *cg_cleanup_sev;
1992 	CLASS(fd, f)(source_fd);
1993 	struct kvm *source_kvm;
1994 	bool charged = false;
1995 	int ret;
1996 
1997 	if (fd_empty(f))
1998 		return -EBADF;
1999 
2000 	if (!file_is_kvm(fd_file(f)))
2001 		return -EBADF;
2002 
2003 	source_kvm = fd_file(f)->private_data;
2004 	ret = sev_lock_two_vms(kvm, source_kvm);
2005 	if (ret)
2006 		return ret;
2007 
2008 	if (kvm->arch.vm_type != source_kvm->arch.vm_type ||
2009 	    sev_guest(kvm) || !sev_guest(source_kvm)) {
2010 		ret = -EINVAL;
2011 		goto out_unlock;
2012 	}
2013 
2014 	src_sev = to_kvm_sev_info(source_kvm);
2015 
2016 	dst_sev->misc_cg = get_current_misc_cg();
2017 	cg_cleanup_sev = dst_sev;
2018 	if (dst_sev->misc_cg != src_sev->misc_cg) {
2019 		ret = sev_misc_cg_try_charge(dst_sev);
2020 		if (ret)
2021 			goto out_dst_cgroup;
2022 		charged = true;
2023 	}
2024 
2025 	ret = kvm_lock_all_vcpus(kvm);
2026 	if (ret)
2027 		goto out_dst_cgroup;
2028 	ret = kvm_lock_all_vcpus(source_kvm);
2029 	if (ret)
2030 		goto out_dst_vcpu;
2031 
2032 	ret = sev_check_source_vcpus(kvm, source_kvm);
2033 	if (ret)
2034 		goto out_source_vcpu;
2035 
2036 	sev_migrate_from(kvm, source_kvm);
2037 	kvm_vm_dead(source_kvm);
2038 	cg_cleanup_sev = src_sev;
2039 	ret = 0;
2040 
2041 out_source_vcpu:
2042 	kvm_unlock_all_vcpus(source_kvm);
2043 out_dst_vcpu:
2044 	kvm_unlock_all_vcpus(kvm);
2045 out_dst_cgroup:
2046 	/* Operates on the source on success, on the destination on failure.  */
2047 	if (charged)
2048 		sev_misc_cg_uncharge(cg_cleanup_sev);
2049 	put_misc_cg(cg_cleanup_sev->misc_cg);
2050 	cg_cleanup_sev->misc_cg = NULL;
2051 out_unlock:
2052 	sev_unlock_two_vms(kvm, source_kvm);
2053 	return ret;
2054 }
2055 
2056 int sev_dev_get_attr(u32 group, u64 attr, u64 *val)
2057 {
2058 	if (group != KVM_X86_GRP_SEV)
2059 		return -ENXIO;
2060 
2061 	switch (attr) {
2062 	case KVM_X86_SEV_VMSA_FEATURES:
2063 		*val = sev_supported_vmsa_features;
2064 		return 0;
2065 
2066 	default:
2067 		return -ENXIO;
2068 	}
2069 }
2070 
2071 /*
2072  * The guest context contains all the information, keys and metadata
2073  * associated with the guest that the firmware tracks to implement SEV
2074  * and SNP features. The firmware stores the guest context in hypervisor
2075  * provide page via the SNP_GCTX_CREATE command.
2076  */
2077 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
2078 {
2079 	struct sev_data_snp_addr data = {};
2080 	void *context;
2081 	int rc;
2082 
2083 	/* Allocate memory for context page */
2084 	context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
2085 	if (!context)
2086 		return NULL;
2087 
2088 	data.address = __psp_pa(context);
2089 	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
2090 	if (rc) {
2091 		pr_warn("Failed to create SEV-SNP context, rc %d fw_error %d",
2092 			rc, argp->error);
2093 		snp_free_firmware_page(context);
2094 		return NULL;
2095 	}
2096 
2097 	return context;
2098 }
2099 
2100 static int snp_bind_asid(struct kvm *kvm, int *error)
2101 {
2102 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2103 	struct sev_data_snp_activate data = {0};
2104 
2105 	data.gctx_paddr = __psp_pa(sev->snp_context);
2106 	data.asid = sev_get_asid(kvm);
2107 	return sev_issue_cmd(kvm, SEV_CMD_SNP_ACTIVATE, &data, error);
2108 }
2109 
2110 static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
2111 {
2112 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2113 	struct sev_data_snp_launch_start start = {0};
2114 	struct kvm_sev_snp_launch_start params;
2115 	int rc;
2116 
2117 	if (!sev_snp_guest(kvm))
2118 		return -ENOTTY;
2119 
2120 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
2121 		return -EFAULT;
2122 
2123 	/* Don't allow userspace to allocate memory for more than 1 SNP context. */
2124 	if (sev->snp_context)
2125 		return -EINVAL;
2126 
2127 	if (params.flags)
2128 		return -EINVAL;
2129 
2130 	if (params.policy & ~SNP_POLICY_MASK_VALID)
2131 		return -EINVAL;
2132 
2133 	/* Check for policy bits that must be set */
2134 	if (!(params.policy & SNP_POLICY_MASK_RSVD_MBO) ||
2135 	    !(params.policy & SNP_POLICY_MASK_SMT))
2136 		return -EINVAL;
2137 
2138 	if (params.policy & SNP_POLICY_MASK_SINGLE_SOCKET)
2139 		return -EINVAL;
2140 
2141 	sev->policy = params.policy;
2142 
2143 	sev->snp_context = snp_context_create(kvm, argp);
2144 	if (!sev->snp_context)
2145 		return -ENOTTY;
2146 
2147 	start.gctx_paddr = __psp_pa(sev->snp_context);
2148 	start.policy = params.policy;
2149 	memcpy(start.gosvw, params.gosvw, sizeof(params.gosvw));
2150 	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_START, &start, &argp->error);
2151 	if (rc) {
2152 		pr_debug("%s: SEV_CMD_SNP_LAUNCH_START firmware command failed, rc %d\n",
2153 			 __func__, rc);
2154 		goto e_free_context;
2155 	}
2156 
2157 	sev->fd = argp->sev_fd;
2158 	rc = snp_bind_asid(kvm, &argp->error);
2159 	if (rc) {
2160 		pr_debug("%s: Failed to bind ASID to SEV-SNP context, rc %d\n",
2161 			 __func__, rc);
2162 		goto e_free_context;
2163 	}
2164 
2165 	return 0;
2166 
2167 e_free_context:
2168 	snp_decommission_context(kvm);
2169 
2170 	return rc;
2171 }
2172 
2173 struct sev_gmem_populate_args {
2174 	__u8 type;
2175 	int sev_fd;
2176 	int fw_error;
2177 };
2178 
2179 static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn_start, kvm_pfn_t pfn,
2180 				  void __user *src, int order, void *opaque)
2181 {
2182 	struct sev_gmem_populate_args *sev_populate_args = opaque;
2183 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2184 	int n_private = 0, ret, i;
2185 	int npages = (1 << order);
2186 	gfn_t gfn;
2187 
2188 	if (WARN_ON_ONCE(sev_populate_args->type != KVM_SEV_SNP_PAGE_TYPE_ZERO && !src))
2189 		return -EINVAL;
2190 
2191 	for (gfn = gfn_start, i = 0; gfn < gfn_start + npages; gfn++, i++) {
2192 		struct sev_data_snp_launch_update fw_args = {0};
2193 		bool assigned = false;
2194 		int level;
2195 
2196 		ret = snp_lookup_rmpentry((u64)pfn + i, &assigned, &level);
2197 		if (ret || assigned) {
2198 			pr_debug("%s: Failed to ensure GFN 0x%llx RMP entry is initial shared state, ret: %d assigned: %d\n",
2199 				 __func__, gfn, ret, assigned);
2200 			ret = ret ? -EINVAL : -EEXIST;
2201 			goto err;
2202 		}
2203 
2204 		if (src) {
2205 			void *vaddr = kmap_local_pfn(pfn + i);
2206 
2207 			if (copy_from_user(vaddr, src + i * PAGE_SIZE, PAGE_SIZE)) {
2208 				ret = -EFAULT;
2209 				goto err;
2210 			}
2211 			kunmap_local(vaddr);
2212 		}
2213 
2214 		ret = rmp_make_private(pfn + i, gfn << PAGE_SHIFT, PG_LEVEL_4K,
2215 				       sev_get_asid(kvm), true);
2216 		if (ret)
2217 			goto err;
2218 
2219 		n_private++;
2220 
2221 		fw_args.gctx_paddr = __psp_pa(sev->snp_context);
2222 		fw_args.address = __sme_set(pfn_to_hpa(pfn + i));
2223 		fw_args.page_size = PG_LEVEL_TO_RMP(PG_LEVEL_4K);
2224 		fw_args.page_type = sev_populate_args->type;
2225 
2226 		ret = __sev_issue_cmd(sev_populate_args->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
2227 				      &fw_args, &sev_populate_args->fw_error);
2228 		if (ret)
2229 			goto fw_err;
2230 	}
2231 
2232 	return 0;
2233 
2234 fw_err:
2235 	/*
2236 	 * If the firmware command failed handle the reclaim and cleanup of that
2237 	 * PFN specially vs. prior pages which can be cleaned up below without
2238 	 * needing to reclaim in advance.
2239 	 *
2240 	 * Additionally, when invalid CPUID function entries are detected,
2241 	 * firmware writes the expected values into the page and leaves it
2242 	 * unencrypted so it can be used for debugging and error-reporting.
2243 	 *
2244 	 * Copy this page back into the source buffer so userspace can use this
2245 	 * information to provide information on which CPUID leaves/fields
2246 	 * failed CPUID validation.
2247 	 */
2248 	if (!snp_page_reclaim(kvm, pfn + i) &&
2249 	    sev_populate_args->type == KVM_SEV_SNP_PAGE_TYPE_CPUID &&
2250 	    sev_populate_args->fw_error == SEV_RET_INVALID_PARAM) {
2251 		void *vaddr = kmap_local_pfn(pfn + i);
2252 
2253 		if (copy_to_user(src + i * PAGE_SIZE, vaddr, PAGE_SIZE))
2254 			pr_debug("Failed to write CPUID page back to userspace\n");
2255 
2256 		kunmap_local(vaddr);
2257 	}
2258 
2259 	/* pfn + i is hypervisor-owned now, so skip below cleanup for it. */
2260 	n_private--;
2261 
2262 err:
2263 	pr_debug("%s: exiting with error ret %d (fw_error %d), restoring %d gmem PFNs to shared.\n",
2264 		 __func__, ret, sev_populate_args->fw_error, n_private);
2265 	for (i = 0; i < n_private; i++)
2266 		kvm_rmp_make_shared(kvm, pfn + i, PG_LEVEL_4K);
2267 
2268 	return ret;
2269 }
2270 
2271 static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
2272 {
2273 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2274 	struct sev_gmem_populate_args sev_populate_args = {0};
2275 	struct kvm_sev_snp_launch_update params;
2276 	struct kvm_memory_slot *memslot;
2277 	long npages, count;
2278 	void __user *src;
2279 	int ret = 0;
2280 
2281 	if (!sev_snp_guest(kvm) || !sev->snp_context)
2282 		return -EINVAL;
2283 
2284 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
2285 		return -EFAULT;
2286 
2287 	pr_debug("%s: GFN start 0x%llx length 0x%llx type %d flags %d\n", __func__,
2288 		 params.gfn_start, params.len, params.type, params.flags);
2289 
2290 	if (!PAGE_ALIGNED(params.len) || params.flags ||
2291 	    (params.type != KVM_SEV_SNP_PAGE_TYPE_NORMAL &&
2292 	     params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO &&
2293 	     params.type != KVM_SEV_SNP_PAGE_TYPE_UNMEASURED &&
2294 	     params.type != KVM_SEV_SNP_PAGE_TYPE_SECRETS &&
2295 	     params.type != KVM_SEV_SNP_PAGE_TYPE_CPUID))
2296 		return -EINVAL;
2297 
2298 	npages = params.len / PAGE_SIZE;
2299 
2300 	/*
2301 	 * For each GFN that's being prepared as part of the initial guest
2302 	 * state, the following pre-conditions are verified:
2303 	 *
2304 	 *   1) The backing memslot is a valid private memslot.
2305 	 *   2) The GFN has been set to private via KVM_SET_MEMORY_ATTRIBUTES
2306 	 *      beforehand.
2307 	 *   3) The PFN of the guest_memfd has not already been set to private
2308 	 *      in the RMP table.
2309 	 *
2310 	 * The KVM MMU relies on kvm->mmu_invalidate_seq to retry nested page
2311 	 * faults if there's a race between a fault and an attribute update via
2312 	 * KVM_SET_MEMORY_ATTRIBUTES, and a similar approach could be utilized
2313 	 * here. However, kvm->slots_lock guards against both this as well as
2314 	 * concurrent memslot updates occurring while these checks are being
2315 	 * performed, so use that here to make it easier to reason about the
2316 	 * initial expected state and better guard against unexpected
2317 	 * situations.
2318 	 */
2319 	mutex_lock(&kvm->slots_lock);
2320 
2321 	memslot = gfn_to_memslot(kvm, params.gfn_start);
2322 	if (!kvm_slot_can_be_private(memslot)) {
2323 		ret = -EINVAL;
2324 		goto out;
2325 	}
2326 
2327 	sev_populate_args.sev_fd = argp->sev_fd;
2328 	sev_populate_args.type = params.type;
2329 	src = params.type == KVM_SEV_SNP_PAGE_TYPE_ZERO ? NULL : u64_to_user_ptr(params.uaddr);
2330 
2331 	count = kvm_gmem_populate(kvm, params.gfn_start, src, npages,
2332 				  sev_gmem_post_populate, &sev_populate_args);
2333 	if (count < 0) {
2334 		argp->error = sev_populate_args.fw_error;
2335 		pr_debug("%s: kvm_gmem_populate failed, ret %ld (fw_error %d)\n",
2336 			 __func__, count, argp->error);
2337 		ret = -EIO;
2338 	} else {
2339 		params.gfn_start += count;
2340 		params.len -= count * PAGE_SIZE;
2341 		if (params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO)
2342 			params.uaddr += count * PAGE_SIZE;
2343 
2344 		ret = 0;
2345 		if (copy_to_user(u64_to_user_ptr(argp->data), &params, sizeof(params)))
2346 			ret = -EFAULT;
2347 	}
2348 
2349 out:
2350 	mutex_unlock(&kvm->slots_lock);
2351 
2352 	return ret;
2353 }
2354 
2355 static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
2356 {
2357 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2358 	struct sev_data_snp_launch_update data = {};
2359 	struct kvm_vcpu *vcpu;
2360 	unsigned long i;
2361 	int ret;
2362 
2363 	data.gctx_paddr = __psp_pa(sev->snp_context);
2364 	data.page_type = SNP_PAGE_TYPE_VMSA;
2365 
2366 	kvm_for_each_vcpu(i, vcpu, kvm) {
2367 		struct vcpu_svm *svm = to_svm(vcpu);
2368 		u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
2369 
2370 		ret = sev_es_sync_vmsa(svm);
2371 		if (ret)
2372 			return ret;
2373 
2374 		/* Transition the VMSA page to a firmware state. */
2375 		ret = rmp_make_private(pfn, INITIAL_VMSA_GPA, PG_LEVEL_4K, sev->asid, true);
2376 		if (ret)
2377 			return ret;
2378 
2379 		/* Issue the SNP command to encrypt the VMSA */
2380 		data.address = __sme_pa(svm->sev_es.vmsa);
2381 		ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
2382 				      &data, &argp->error);
2383 		if (ret) {
2384 			snp_page_reclaim(kvm, pfn);
2385 
2386 			return ret;
2387 		}
2388 
2389 		svm->vcpu.arch.guest_state_protected = true;
2390 		/*
2391 		 * SEV-ES (and thus SNP) guest mandates LBR Virtualization to
2392 		 * be _always_ ON. Enable it only after setting
2393 		 * guest_state_protected because KVM_SET_MSRS allows dynamic
2394 		 * toggling of LBRV (for performance reason) on write access to
2395 		 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set.
2396 		 */
2397 		svm_enable_lbrv(vcpu);
2398 	}
2399 
2400 	return 0;
2401 }
2402 
2403 static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
2404 {
2405 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2406 	struct kvm_sev_snp_launch_finish params;
2407 	struct sev_data_snp_launch_finish *data;
2408 	void *id_block = NULL, *id_auth = NULL;
2409 	int ret;
2410 
2411 	if (!sev_snp_guest(kvm))
2412 		return -ENOTTY;
2413 
2414 	if (!sev->snp_context)
2415 		return -EINVAL;
2416 
2417 	if (copy_from_user(&params, u64_to_user_ptr(argp->data), sizeof(params)))
2418 		return -EFAULT;
2419 
2420 	if (params.flags)
2421 		return -EINVAL;
2422 
2423 	/* Measure all vCPUs using LAUNCH_UPDATE before finalizing the launch flow. */
2424 	ret = snp_launch_update_vmsa(kvm, argp);
2425 	if (ret)
2426 		return ret;
2427 
2428 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
2429 	if (!data)
2430 		return -ENOMEM;
2431 
2432 	if (params.id_block_en) {
2433 		id_block = psp_copy_user_blob(params.id_block_uaddr, KVM_SEV_SNP_ID_BLOCK_SIZE);
2434 		if (IS_ERR(id_block)) {
2435 			ret = PTR_ERR(id_block);
2436 			goto e_free;
2437 		}
2438 
2439 		data->id_block_en = 1;
2440 		data->id_block_paddr = __sme_pa(id_block);
2441 
2442 		id_auth = psp_copy_user_blob(params.id_auth_uaddr, KVM_SEV_SNP_ID_AUTH_SIZE);
2443 		if (IS_ERR(id_auth)) {
2444 			ret = PTR_ERR(id_auth);
2445 			goto e_free_id_block;
2446 		}
2447 
2448 		data->id_auth_paddr = __sme_pa(id_auth);
2449 
2450 		if (params.auth_key_en)
2451 			data->auth_key_en = 1;
2452 	}
2453 
2454 	data->vcek_disabled = params.vcek_disabled;
2455 
2456 	memcpy(data->host_data, params.host_data, KVM_SEV_SNP_FINISH_DATA_SIZE);
2457 	data->gctx_paddr = __psp_pa(sev->snp_context);
2458 	ret = sev_issue_cmd(kvm, SEV_CMD_SNP_LAUNCH_FINISH, data, &argp->error);
2459 
2460 	/*
2461 	 * Now that there will be no more SNP_LAUNCH_UPDATE ioctls, private pages
2462 	 * can be given to the guest simply by marking the RMP entry as private.
2463 	 * This can happen on first access and also with KVM_PRE_FAULT_MEMORY.
2464 	 */
2465 	if (!ret)
2466 		kvm->arch.pre_fault_allowed = true;
2467 
2468 	kfree(id_auth);
2469 
2470 e_free_id_block:
2471 	kfree(id_block);
2472 
2473 e_free:
2474 	kfree(data);
2475 
2476 	return ret;
2477 }
2478 
2479 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
2480 {
2481 	struct kvm_sev_cmd sev_cmd;
2482 	int r;
2483 
2484 	if (!sev_enabled)
2485 		return -ENOTTY;
2486 
2487 	if (!argp)
2488 		return 0;
2489 
2490 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
2491 		return -EFAULT;
2492 
2493 	mutex_lock(&kvm->lock);
2494 
2495 	/* Only the enc_context_owner handles some memory enc operations. */
2496 	if (is_mirroring_enc_context(kvm) &&
2497 	    !is_cmd_allowed_from_mirror(sev_cmd.id)) {
2498 		r = -EINVAL;
2499 		goto out;
2500 	}
2501 
2502 	/*
2503 	 * Once KVM_SEV_INIT2 initializes a KVM instance as an SNP guest, only
2504 	 * allow the use of SNP-specific commands.
2505 	 */
2506 	if (sev_snp_guest(kvm) && sev_cmd.id < KVM_SEV_SNP_LAUNCH_START) {
2507 		r = -EPERM;
2508 		goto out;
2509 	}
2510 
2511 	switch (sev_cmd.id) {
2512 	case KVM_SEV_ES_INIT:
2513 		if (!sev_es_enabled) {
2514 			r = -ENOTTY;
2515 			goto out;
2516 		}
2517 		fallthrough;
2518 	case KVM_SEV_INIT:
2519 		r = sev_guest_init(kvm, &sev_cmd);
2520 		break;
2521 	case KVM_SEV_INIT2:
2522 		r = sev_guest_init2(kvm, &sev_cmd);
2523 		break;
2524 	case KVM_SEV_LAUNCH_START:
2525 		r = sev_launch_start(kvm, &sev_cmd);
2526 		break;
2527 	case KVM_SEV_LAUNCH_UPDATE_DATA:
2528 		r = sev_launch_update_data(kvm, &sev_cmd);
2529 		break;
2530 	case KVM_SEV_LAUNCH_UPDATE_VMSA:
2531 		r = sev_launch_update_vmsa(kvm, &sev_cmd);
2532 		break;
2533 	case KVM_SEV_LAUNCH_MEASURE:
2534 		r = sev_launch_measure(kvm, &sev_cmd);
2535 		break;
2536 	case KVM_SEV_LAUNCH_FINISH:
2537 		r = sev_launch_finish(kvm, &sev_cmd);
2538 		break;
2539 	case KVM_SEV_GUEST_STATUS:
2540 		r = sev_guest_status(kvm, &sev_cmd);
2541 		break;
2542 	case KVM_SEV_DBG_DECRYPT:
2543 		r = sev_dbg_crypt(kvm, &sev_cmd, true);
2544 		break;
2545 	case KVM_SEV_DBG_ENCRYPT:
2546 		r = sev_dbg_crypt(kvm, &sev_cmd, false);
2547 		break;
2548 	case KVM_SEV_LAUNCH_SECRET:
2549 		r = sev_launch_secret(kvm, &sev_cmd);
2550 		break;
2551 	case KVM_SEV_GET_ATTESTATION_REPORT:
2552 		r = sev_get_attestation_report(kvm, &sev_cmd);
2553 		break;
2554 	case KVM_SEV_SEND_START:
2555 		r = sev_send_start(kvm, &sev_cmd);
2556 		break;
2557 	case KVM_SEV_SEND_UPDATE_DATA:
2558 		r = sev_send_update_data(kvm, &sev_cmd);
2559 		break;
2560 	case KVM_SEV_SEND_FINISH:
2561 		r = sev_send_finish(kvm, &sev_cmd);
2562 		break;
2563 	case KVM_SEV_SEND_CANCEL:
2564 		r = sev_send_cancel(kvm, &sev_cmd);
2565 		break;
2566 	case KVM_SEV_RECEIVE_START:
2567 		r = sev_receive_start(kvm, &sev_cmd);
2568 		break;
2569 	case KVM_SEV_RECEIVE_UPDATE_DATA:
2570 		r = sev_receive_update_data(kvm, &sev_cmd);
2571 		break;
2572 	case KVM_SEV_RECEIVE_FINISH:
2573 		r = sev_receive_finish(kvm, &sev_cmd);
2574 		break;
2575 	case KVM_SEV_SNP_LAUNCH_START:
2576 		r = snp_launch_start(kvm, &sev_cmd);
2577 		break;
2578 	case KVM_SEV_SNP_LAUNCH_UPDATE:
2579 		r = snp_launch_update(kvm, &sev_cmd);
2580 		break;
2581 	case KVM_SEV_SNP_LAUNCH_FINISH:
2582 		r = snp_launch_finish(kvm, &sev_cmd);
2583 		break;
2584 	default:
2585 		r = -EINVAL;
2586 		goto out;
2587 	}
2588 
2589 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
2590 		r = -EFAULT;
2591 
2592 out:
2593 	mutex_unlock(&kvm->lock);
2594 	return r;
2595 }
2596 
2597 int sev_mem_enc_register_region(struct kvm *kvm,
2598 				struct kvm_enc_region *range)
2599 {
2600 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2601 	struct enc_region *region;
2602 	int ret = 0;
2603 
2604 	if (!sev_guest(kvm))
2605 		return -ENOTTY;
2606 
2607 	/* If kvm is mirroring encryption context it isn't responsible for it */
2608 	if (is_mirroring_enc_context(kvm))
2609 		return -EINVAL;
2610 
2611 	if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
2612 		return -EINVAL;
2613 
2614 	region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
2615 	if (!region)
2616 		return -ENOMEM;
2617 
2618 	mutex_lock(&kvm->lock);
2619 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages,
2620 				       FOLL_WRITE | FOLL_LONGTERM);
2621 	if (IS_ERR(region->pages)) {
2622 		ret = PTR_ERR(region->pages);
2623 		mutex_unlock(&kvm->lock);
2624 		goto e_free;
2625 	}
2626 
2627 	/*
2628 	 * The guest may change the memory encryption attribute from C=0 -> C=1
2629 	 * or vice versa for this memory range. Lets make sure caches are
2630 	 * flushed to ensure that guest data gets written into memory with
2631 	 * correct C-bit.  Note, this must be done before dropping kvm->lock,
2632 	 * as region and its array of pages can be freed by a different task
2633 	 * once kvm->lock is released.
2634 	 */
2635 	sev_clflush_pages(region->pages, region->npages);
2636 
2637 	region->uaddr = range->addr;
2638 	region->size = range->size;
2639 
2640 	list_add_tail(&region->list, &sev->regions_list);
2641 	mutex_unlock(&kvm->lock);
2642 
2643 	return ret;
2644 
2645 e_free:
2646 	kfree(region);
2647 	return ret;
2648 }
2649 
2650 static struct enc_region *
2651 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
2652 {
2653 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2654 	struct list_head *head = &sev->regions_list;
2655 	struct enc_region *i;
2656 
2657 	list_for_each_entry(i, head, list) {
2658 		if (i->uaddr == range->addr &&
2659 		    i->size == range->size)
2660 			return i;
2661 	}
2662 
2663 	return NULL;
2664 }
2665 
2666 static void __unregister_enc_region_locked(struct kvm *kvm,
2667 					   struct enc_region *region)
2668 {
2669 	sev_unpin_memory(kvm, region->pages, region->npages);
2670 	list_del(&region->list);
2671 	kfree(region);
2672 }
2673 
2674 int sev_mem_enc_unregister_region(struct kvm *kvm,
2675 				  struct kvm_enc_region *range)
2676 {
2677 	struct enc_region *region;
2678 	int ret;
2679 
2680 	/* If kvm is mirroring encryption context it isn't responsible for it */
2681 	if (is_mirroring_enc_context(kvm))
2682 		return -EINVAL;
2683 
2684 	mutex_lock(&kvm->lock);
2685 
2686 	if (!sev_guest(kvm)) {
2687 		ret = -ENOTTY;
2688 		goto failed;
2689 	}
2690 
2691 	region = find_enc_region(kvm, range);
2692 	if (!region) {
2693 		ret = -EINVAL;
2694 		goto failed;
2695 	}
2696 
2697 	/*
2698 	 * Ensure that all guest tagged cache entries are flushed before
2699 	 * releasing the pages back to the system for use. CLFLUSH will
2700 	 * not do this, so issue a WBINVD.
2701 	 */
2702 	wbinvd_on_all_cpus();
2703 
2704 	__unregister_enc_region_locked(kvm, region);
2705 
2706 	mutex_unlock(&kvm->lock);
2707 	return 0;
2708 
2709 failed:
2710 	mutex_unlock(&kvm->lock);
2711 	return ret;
2712 }
2713 
2714 int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2715 {
2716 	CLASS(fd, f)(source_fd);
2717 	struct kvm *source_kvm;
2718 	struct kvm_sev_info *source_sev, *mirror_sev;
2719 	int ret;
2720 
2721 	if (fd_empty(f))
2722 		return -EBADF;
2723 
2724 	if (!file_is_kvm(fd_file(f)))
2725 		return -EBADF;
2726 
2727 	source_kvm = fd_file(f)->private_data;
2728 	ret = sev_lock_two_vms(kvm, source_kvm);
2729 	if (ret)
2730 		return ret;
2731 
2732 	/*
2733 	 * Mirrors of mirrors should work, but let's not get silly.  Also
2734 	 * disallow out-of-band SEV/SEV-ES init if the target is already an
2735 	 * SEV guest, or if vCPUs have been created.  KVM relies on vCPUs being
2736 	 * created after SEV/SEV-ES initialization, e.g. to init intercepts.
2737 	 */
2738 	if (sev_guest(kvm) || !sev_guest(source_kvm) ||
2739 	    is_mirroring_enc_context(source_kvm) || kvm->created_vcpus) {
2740 		ret = -EINVAL;
2741 		goto e_unlock;
2742 	}
2743 
2744 	/*
2745 	 * The mirror kvm holds an enc_context_owner ref so its asid can't
2746 	 * disappear until we're done with it
2747 	 */
2748 	source_sev = to_kvm_sev_info(source_kvm);
2749 	kvm_get_kvm(source_kvm);
2750 	mirror_sev = to_kvm_sev_info(kvm);
2751 	list_add_tail(&mirror_sev->mirror_entry, &source_sev->mirror_vms);
2752 
2753 	/* Set enc_context_owner and copy its encryption context over */
2754 	mirror_sev->enc_context_owner = source_kvm;
2755 	mirror_sev->active = true;
2756 	mirror_sev->asid = source_sev->asid;
2757 	mirror_sev->fd = source_sev->fd;
2758 	mirror_sev->es_active = source_sev->es_active;
2759 	mirror_sev->need_init = false;
2760 	mirror_sev->handle = source_sev->handle;
2761 	INIT_LIST_HEAD(&mirror_sev->regions_list);
2762 	INIT_LIST_HEAD(&mirror_sev->mirror_vms);
2763 	ret = 0;
2764 
2765 	/*
2766 	 * Do not copy ap_jump_table. Since the mirror does not share the same
2767 	 * KVM contexts as the original, and they may have different
2768 	 * memory-views.
2769 	 */
2770 
2771 e_unlock:
2772 	sev_unlock_two_vms(kvm, source_kvm);
2773 	return ret;
2774 }
2775 
2776 static int snp_decommission_context(struct kvm *kvm)
2777 {
2778 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2779 	struct sev_data_snp_addr data = {};
2780 	int ret;
2781 
2782 	/* If context is not created then do nothing */
2783 	if (!sev->snp_context)
2784 		return 0;
2785 
2786 	/* Do the decommision, which will unbind the ASID from the SNP context */
2787 	data.address = __sme_pa(sev->snp_context);
2788 	down_write(&sev_deactivate_lock);
2789 	ret = sev_do_cmd(SEV_CMD_SNP_DECOMMISSION, &data, NULL);
2790 	up_write(&sev_deactivate_lock);
2791 
2792 	if (WARN_ONCE(ret, "Failed to release guest context, ret %d", ret))
2793 		return ret;
2794 
2795 	snp_free_firmware_page(sev->snp_context);
2796 	sev->snp_context = NULL;
2797 
2798 	return 0;
2799 }
2800 
2801 void sev_vm_destroy(struct kvm *kvm)
2802 {
2803 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
2804 	struct list_head *head = &sev->regions_list;
2805 	struct list_head *pos, *q;
2806 
2807 	if (!sev_guest(kvm))
2808 		return;
2809 
2810 	WARN_ON(!list_empty(&sev->mirror_vms));
2811 
2812 	/* If this is a mirror_kvm release the enc_context_owner and skip sev cleanup */
2813 	if (is_mirroring_enc_context(kvm)) {
2814 		struct kvm *owner_kvm = sev->enc_context_owner;
2815 
2816 		mutex_lock(&owner_kvm->lock);
2817 		list_del(&sev->mirror_entry);
2818 		mutex_unlock(&owner_kvm->lock);
2819 		kvm_put_kvm(owner_kvm);
2820 		return;
2821 	}
2822 
2823 	/*
2824 	 * Ensure that all guest tagged cache entries are flushed before
2825 	 * releasing the pages back to the system for use. CLFLUSH will
2826 	 * not do this, so issue a WBINVD.
2827 	 */
2828 	wbinvd_on_all_cpus();
2829 
2830 	/*
2831 	 * if userspace was terminated before unregistering the memory regions
2832 	 * then lets unpin all the registered memory.
2833 	 */
2834 	if (!list_empty(head)) {
2835 		list_for_each_safe(pos, q, head) {
2836 			__unregister_enc_region_locked(kvm,
2837 				list_entry(pos, struct enc_region, list));
2838 			cond_resched();
2839 		}
2840 	}
2841 
2842 	if (sev_snp_guest(kvm)) {
2843 		snp_guest_req_cleanup(kvm);
2844 
2845 		/*
2846 		 * Decomission handles unbinding of the ASID. If it fails for
2847 		 * some unexpected reason, just leak the ASID.
2848 		 */
2849 		if (snp_decommission_context(kvm))
2850 			return;
2851 	} else {
2852 		sev_unbind_asid(kvm, sev->handle);
2853 	}
2854 
2855 	sev_asid_free(sev);
2856 }
2857 
2858 void __init sev_set_cpu_caps(void)
2859 {
2860 	if (sev_enabled) {
2861 		kvm_cpu_cap_set(X86_FEATURE_SEV);
2862 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SEV_VM);
2863 	}
2864 	if (sev_es_enabled) {
2865 		kvm_cpu_cap_set(X86_FEATURE_SEV_ES);
2866 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SEV_ES_VM);
2867 	}
2868 	if (sev_snp_enabled) {
2869 		kvm_cpu_cap_set(X86_FEATURE_SEV_SNP);
2870 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SNP_VM);
2871 	}
2872 }
2873 
2874 void __init sev_hardware_setup(void)
2875 {
2876 	unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count;
2877 	struct sev_platform_init_args init_args = {0};
2878 	bool sev_snp_supported = false;
2879 	bool sev_es_supported = false;
2880 	bool sev_supported = false;
2881 
2882 	if (!sev_enabled || !npt_enabled || !nrips)
2883 		goto out;
2884 
2885 	/*
2886 	 * SEV must obviously be supported in hardware.  Sanity check that the
2887 	 * CPU supports decode assists, which is mandatory for SEV guests to
2888 	 * support instruction emulation.  Ditto for flushing by ASID, as SEV
2889 	 * guests are bound to a single ASID, i.e. KVM can't rotate to a new
2890 	 * ASID to effect a TLB flush.
2891 	 */
2892 	if (!boot_cpu_has(X86_FEATURE_SEV) ||
2893 	    WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_DECODEASSISTS)) ||
2894 	    WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_FLUSHBYASID)))
2895 		goto out;
2896 
2897 	/*
2898 	 * The kernel's initcall infrastructure lacks the ability to express
2899 	 * dependencies between initcalls, whereas the modules infrastructure
2900 	 * automatically handles dependencies via symbol loading.  Ensure the
2901 	 * PSP SEV driver is initialized before proceeding if KVM is built-in,
2902 	 * as the dependency isn't handled by the initcall infrastructure.
2903 	 */
2904 	if (IS_BUILTIN(CONFIG_KVM_AMD) && sev_module_init())
2905 		goto out;
2906 
2907 	/* Retrieve SEV CPUID information */
2908 	cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
2909 
2910 	/* Set encryption bit location for SEV-ES guests */
2911 	sev_enc_bit = ebx & 0x3f;
2912 
2913 	/* Maximum number of encrypted guests supported simultaneously */
2914 	max_sev_asid = ecx;
2915 	if (!max_sev_asid)
2916 		goto out;
2917 
2918 	/* Minimum ASID value that should be used for SEV guest */
2919 	min_sev_asid = edx;
2920 	sev_me_mask = 1UL << (ebx & 0x3f);
2921 
2922 	/*
2923 	 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap,
2924 	 * even though it's never used, so that the bitmap is indexed by the
2925 	 * actual ASID.
2926 	 */
2927 	nr_asids = max_sev_asid + 1;
2928 	sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
2929 	if (!sev_asid_bitmap)
2930 		goto out;
2931 
2932 	sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
2933 	if (!sev_reclaim_asid_bitmap) {
2934 		bitmap_free(sev_asid_bitmap);
2935 		sev_asid_bitmap = NULL;
2936 		goto out;
2937 	}
2938 
2939 	if (min_sev_asid <= max_sev_asid) {
2940 		sev_asid_count = max_sev_asid - min_sev_asid + 1;
2941 		WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count));
2942 	}
2943 	sev_supported = true;
2944 
2945 	/* SEV-ES support requested? */
2946 	if (!sev_es_enabled)
2947 		goto out;
2948 
2949 	/*
2950 	 * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
2951 	 * instruction stream, i.e. can't emulate in response to a #NPF and
2952 	 * instead relies on #NPF(RSVD) being reflected into the guest as #VC
2953 	 * (the guest can then do a #VMGEXIT to request MMIO emulation).
2954 	 */
2955 	if (!enable_mmio_caching)
2956 		goto out;
2957 
2958 	/* Does the CPU support SEV-ES? */
2959 	if (!boot_cpu_has(X86_FEATURE_SEV_ES))
2960 		goto out;
2961 
2962 	if (!lbrv) {
2963 		WARN_ONCE(!boot_cpu_has(X86_FEATURE_LBRV),
2964 			  "LBRV must be present for SEV-ES support");
2965 		goto out;
2966 	}
2967 
2968 	/* Has the system been allocated ASIDs for SEV-ES? */
2969 	if (min_sev_asid == 1)
2970 		goto out;
2971 
2972 	sev_es_asid_count = min_sev_asid - 1;
2973 	WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count));
2974 	sev_es_supported = true;
2975 	sev_snp_supported = sev_snp_enabled && cc_platform_has(CC_ATTR_HOST_SEV_SNP);
2976 
2977 out:
2978 	if (boot_cpu_has(X86_FEATURE_SEV))
2979 		pr_info("SEV %s (ASIDs %u - %u)\n",
2980 			sev_supported ? min_sev_asid <= max_sev_asid ? "enabled" :
2981 								       "unusable" :
2982 								       "disabled",
2983 			min_sev_asid, max_sev_asid);
2984 	if (boot_cpu_has(X86_FEATURE_SEV_ES))
2985 		pr_info("SEV-ES %s (ASIDs %u - %u)\n",
2986 			str_enabled_disabled(sev_es_supported),
2987 			min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1);
2988 	if (boot_cpu_has(X86_FEATURE_SEV_SNP))
2989 		pr_info("SEV-SNP %s (ASIDs %u - %u)\n",
2990 			str_enabled_disabled(sev_snp_supported),
2991 			min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1);
2992 
2993 	sev_enabled = sev_supported;
2994 	sev_es_enabled = sev_es_supported;
2995 	sev_snp_enabled = sev_snp_supported;
2996 
2997 	if (!sev_es_enabled || !cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) ||
2998 	    !cpu_feature_enabled(X86_FEATURE_NO_NESTED_DATA_BP))
2999 		sev_es_debug_swap_enabled = false;
3000 
3001 	sev_supported_vmsa_features = 0;
3002 	if (sev_es_debug_swap_enabled)
3003 		sev_supported_vmsa_features |= SVM_SEV_FEAT_DEBUG_SWAP;
3004 
3005 	if (!sev_enabled)
3006 		return;
3007 
3008 	/*
3009 	 * Do both SNP and SEV initialization at KVM module load.
3010 	 */
3011 	init_args.probe = true;
3012 	sev_platform_init(&init_args);
3013 }
3014 
3015 void sev_hardware_unsetup(void)
3016 {
3017 	if (!sev_enabled)
3018 		return;
3019 
3020 	/* No need to take sev_bitmap_lock, all VMs have been destroyed. */
3021 	sev_flush_asids(1, max_sev_asid);
3022 
3023 	bitmap_free(sev_asid_bitmap);
3024 	bitmap_free(sev_reclaim_asid_bitmap);
3025 
3026 	misc_cg_set_capacity(MISC_CG_RES_SEV, 0);
3027 	misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0);
3028 
3029 	sev_platform_shutdown();
3030 }
3031 
3032 int sev_cpu_init(struct svm_cpu_data *sd)
3033 {
3034 	if (!sev_enabled)
3035 		return 0;
3036 
3037 	sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL);
3038 	if (!sd->sev_vmcbs)
3039 		return -ENOMEM;
3040 
3041 	return 0;
3042 }
3043 
3044 /*
3045  * Pages used by hardware to hold guest encrypted state must be flushed before
3046  * returning them to the system.
3047  */
3048 static void sev_flush_encrypted_page(struct kvm_vcpu *vcpu, void *va)
3049 {
3050 	unsigned int asid = sev_get_asid(vcpu->kvm);
3051 
3052 	/*
3053 	 * Note!  The address must be a kernel address, as regular page walk
3054 	 * checks are performed by VM_PAGE_FLUSH, i.e. operating on a user
3055 	 * address is non-deterministic and unsafe.  This function deliberately
3056 	 * takes a pointer to deter passing in a user address.
3057 	 */
3058 	unsigned long addr = (unsigned long)va;
3059 
3060 	/*
3061 	 * If CPU enforced cache coherency for encrypted mappings of the
3062 	 * same physical page is supported, use CLFLUSHOPT instead. NOTE: cache
3063 	 * flush is still needed in order to work properly with DMA devices.
3064 	 */
3065 	if (boot_cpu_has(X86_FEATURE_SME_COHERENT)) {
3066 		clflush_cache_range(va, PAGE_SIZE);
3067 		return;
3068 	}
3069 
3070 	/*
3071 	 * VM Page Flush takes a host virtual address and a guest ASID.  Fall
3072 	 * back to WBINVD if this faults so as not to make any problems worse
3073 	 * by leaving stale encrypted data in the cache.
3074 	 */
3075 	if (WARN_ON_ONCE(wrmsrq_safe(MSR_AMD64_VM_PAGE_FLUSH, addr | asid)))
3076 		goto do_wbinvd;
3077 
3078 	return;
3079 
3080 do_wbinvd:
3081 	wbinvd_on_all_cpus();
3082 }
3083 
3084 void sev_guest_memory_reclaimed(struct kvm *kvm)
3085 {
3086 	/*
3087 	 * With SNP+gmem, private/encrypted memory is unreachable via the
3088 	 * hva-based mmu notifiers, so these events are only actually
3089 	 * pertaining to shared pages where there is no need to perform
3090 	 * the WBINVD to flush associated caches.
3091 	 */
3092 	if (!sev_guest(kvm) || sev_snp_guest(kvm))
3093 		return;
3094 
3095 	wbinvd_on_all_cpus();
3096 }
3097 
3098 void sev_free_vcpu(struct kvm_vcpu *vcpu)
3099 {
3100 	struct vcpu_svm *svm;
3101 
3102 	if (!sev_es_guest(vcpu->kvm))
3103 		return;
3104 
3105 	svm = to_svm(vcpu);
3106 
3107 	/*
3108 	 * If it's an SNP guest, then the VMSA was marked in the RMP table as
3109 	 * a guest-owned page. Transition the page to hypervisor state before
3110 	 * releasing it back to the system.
3111 	 */
3112 	if (sev_snp_guest(vcpu->kvm)) {
3113 		u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
3114 
3115 		if (kvm_rmp_make_shared(vcpu->kvm, pfn, PG_LEVEL_4K))
3116 			goto skip_vmsa_free;
3117 	}
3118 
3119 	if (vcpu->arch.guest_state_protected)
3120 		sev_flush_encrypted_page(vcpu, svm->sev_es.vmsa);
3121 
3122 	__free_page(virt_to_page(svm->sev_es.vmsa));
3123 
3124 skip_vmsa_free:
3125 	if (svm->sev_es.ghcb_sa_free)
3126 		kvfree(svm->sev_es.ghcb_sa);
3127 }
3128 
3129 static u64 kvm_ghcb_get_sw_exit_code(struct vmcb_control_area *control)
3130 {
3131 	return (((u64)control->exit_code_hi) << 32) | control->exit_code;
3132 }
3133 
3134 static void dump_ghcb(struct vcpu_svm *svm)
3135 {
3136 	struct vmcb_control_area *control = &svm->vmcb->control;
3137 	unsigned int nbits;
3138 
3139 	/* Re-use the dump_invalid_vmcb module parameter */
3140 	if (!dump_invalid_vmcb) {
3141 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3142 		return;
3143 	}
3144 
3145 	nbits = sizeof(svm->sev_es.valid_bitmap) * 8;
3146 
3147 	/*
3148 	 * Print KVM's snapshot of the GHCB values that were (unsuccessfully)
3149 	 * used to handle the exit.  If the guest has since modified the GHCB
3150 	 * itself, dumping the raw GHCB won't help debug why KVM was unable to
3151 	 * handle the VMGEXIT that KVM observed.
3152 	 */
3153 	pr_err("GHCB (GPA=%016llx) snapshot:\n", svm->vmcb->control.ghcb_gpa);
3154 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
3155 	       kvm_ghcb_get_sw_exit_code(control), kvm_ghcb_sw_exit_code_is_valid(svm));
3156 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
3157 	       control->exit_info_1, kvm_ghcb_sw_exit_info_1_is_valid(svm));
3158 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
3159 	       control->exit_info_2, kvm_ghcb_sw_exit_info_2_is_valid(svm));
3160 	pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
3161 	       svm->sev_es.sw_scratch, kvm_ghcb_sw_scratch_is_valid(svm));
3162 	pr_err("%-20s%*pb\n", "valid_bitmap", nbits, svm->sev_es.valid_bitmap);
3163 }
3164 
3165 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
3166 {
3167 	struct kvm_vcpu *vcpu = &svm->vcpu;
3168 	struct ghcb *ghcb = svm->sev_es.ghcb;
3169 
3170 	/*
3171 	 * The GHCB protocol so far allows for the following data
3172 	 * to be returned:
3173 	 *   GPRs RAX, RBX, RCX, RDX
3174 	 *
3175 	 * Copy their values, even if they may not have been written during the
3176 	 * VM-Exit.  It's the guest's responsibility to not consume random data.
3177 	 */
3178 	ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
3179 	ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
3180 	ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
3181 	ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
3182 }
3183 
3184 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
3185 {
3186 	struct vmcb_control_area *control = &svm->vmcb->control;
3187 	struct kvm_vcpu *vcpu = &svm->vcpu;
3188 	struct ghcb *ghcb = svm->sev_es.ghcb;
3189 	u64 exit_code;
3190 
3191 	/*
3192 	 * The GHCB protocol so far allows for the following data
3193 	 * to be supplied:
3194 	 *   GPRs RAX, RBX, RCX, RDX
3195 	 *   XCR0
3196 	 *   CPL
3197 	 *
3198 	 * VMMCALL allows the guest to provide extra registers. KVM also
3199 	 * expects RSI for hypercalls, so include that, too.
3200 	 *
3201 	 * Copy their values to the appropriate location if supplied.
3202 	 */
3203 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
3204 
3205 	BUILD_BUG_ON(sizeof(svm->sev_es.valid_bitmap) != sizeof(ghcb->save.valid_bitmap));
3206 	memcpy(&svm->sev_es.valid_bitmap, &ghcb->save.valid_bitmap, sizeof(ghcb->save.valid_bitmap));
3207 
3208 	vcpu->arch.regs[VCPU_REGS_RAX] = kvm_ghcb_get_rax_if_valid(svm, ghcb);
3209 	vcpu->arch.regs[VCPU_REGS_RBX] = kvm_ghcb_get_rbx_if_valid(svm, ghcb);
3210 	vcpu->arch.regs[VCPU_REGS_RCX] = kvm_ghcb_get_rcx_if_valid(svm, ghcb);
3211 	vcpu->arch.regs[VCPU_REGS_RDX] = kvm_ghcb_get_rdx_if_valid(svm, ghcb);
3212 	vcpu->arch.regs[VCPU_REGS_RSI] = kvm_ghcb_get_rsi_if_valid(svm, ghcb);
3213 
3214 	svm->vmcb->save.cpl = kvm_ghcb_get_cpl_if_valid(svm, ghcb);
3215 
3216 	if (kvm_ghcb_xcr0_is_valid(svm)) {
3217 		vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb);
3218 		vcpu->arch.cpuid_dynamic_bits_dirty = true;
3219 	}
3220 
3221 	/* Copy the GHCB exit information into the VMCB fields */
3222 	exit_code = ghcb_get_sw_exit_code(ghcb);
3223 	control->exit_code = lower_32_bits(exit_code);
3224 	control->exit_code_hi = upper_32_bits(exit_code);
3225 	control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb);
3226 	control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb);
3227 	svm->sev_es.sw_scratch = kvm_ghcb_get_sw_scratch_if_valid(svm, ghcb);
3228 
3229 	/* Clear the valid entries fields */
3230 	memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
3231 }
3232 
3233 static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
3234 {
3235 	struct vmcb_control_area *control = &svm->vmcb->control;
3236 	struct kvm_vcpu *vcpu = &svm->vcpu;
3237 	u64 exit_code;
3238 	u64 reason;
3239 
3240 	/*
3241 	 * Retrieve the exit code now even though it may not be marked valid
3242 	 * as it could help with debugging.
3243 	 */
3244 	exit_code = kvm_ghcb_get_sw_exit_code(control);
3245 
3246 	/* Only GHCB Usage code 0 is supported */
3247 	if (svm->sev_es.ghcb->ghcb_usage) {
3248 		reason = GHCB_ERR_INVALID_USAGE;
3249 		goto vmgexit_err;
3250 	}
3251 
3252 	reason = GHCB_ERR_MISSING_INPUT;
3253 
3254 	if (!kvm_ghcb_sw_exit_code_is_valid(svm) ||
3255 	    !kvm_ghcb_sw_exit_info_1_is_valid(svm) ||
3256 	    !kvm_ghcb_sw_exit_info_2_is_valid(svm))
3257 		goto vmgexit_err;
3258 
3259 	switch (exit_code) {
3260 	case SVM_EXIT_READ_DR7:
3261 		break;
3262 	case SVM_EXIT_WRITE_DR7:
3263 		if (!kvm_ghcb_rax_is_valid(svm))
3264 			goto vmgexit_err;
3265 		break;
3266 	case SVM_EXIT_RDTSC:
3267 		break;
3268 	case SVM_EXIT_RDPMC:
3269 		if (!kvm_ghcb_rcx_is_valid(svm))
3270 			goto vmgexit_err;
3271 		break;
3272 	case SVM_EXIT_CPUID:
3273 		if (!kvm_ghcb_rax_is_valid(svm) ||
3274 		    !kvm_ghcb_rcx_is_valid(svm))
3275 			goto vmgexit_err;
3276 		if (vcpu->arch.regs[VCPU_REGS_RAX] == 0xd)
3277 			if (!kvm_ghcb_xcr0_is_valid(svm))
3278 				goto vmgexit_err;
3279 		break;
3280 	case SVM_EXIT_INVD:
3281 		break;
3282 	case SVM_EXIT_IOIO:
3283 		if (control->exit_info_1 & SVM_IOIO_STR_MASK) {
3284 			if (!kvm_ghcb_sw_scratch_is_valid(svm))
3285 				goto vmgexit_err;
3286 		} else {
3287 			if (!(control->exit_info_1 & SVM_IOIO_TYPE_MASK))
3288 				if (!kvm_ghcb_rax_is_valid(svm))
3289 					goto vmgexit_err;
3290 		}
3291 		break;
3292 	case SVM_EXIT_MSR:
3293 		if (!kvm_ghcb_rcx_is_valid(svm))
3294 			goto vmgexit_err;
3295 		if (control->exit_info_1) {
3296 			if (!kvm_ghcb_rax_is_valid(svm) ||
3297 			    !kvm_ghcb_rdx_is_valid(svm))
3298 				goto vmgexit_err;
3299 		}
3300 		break;
3301 	case SVM_EXIT_VMMCALL:
3302 		if (!kvm_ghcb_rax_is_valid(svm) ||
3303 		    !kvm_ghcb_cpl_is_valid(svm))
3304 			goto vmgexit_err;
3305 		break;
3306 	case SVM_EXIT_RDTSCP:
3307 		break;
3308 	case SVM_EXIT_WBINVD:
3309 		break;
3310 	case SVM_EXIT_MONITOR:
3311 		if (!kvm_ghcb_rax_is_valid(svm) ||
3312 		    !kvm_ghcb_rcx_is_valid(svm) ||
3313 		    !kvm_ghcb_rdx_is_valid(svm))
3314 			goto vmgexit_err;
3315 		break;
3316 	case SVM_EXIT_MWAIT:
3317 		if (!kvm_ghcb_rax_is_valid(svm) ||
3318 		    !kvm_ghcb_rcx_is_valid(svm))
3319 			goto vmgexit_err;
3320 		break;
3321 	case SVM_VMGEXIT_MMIO_READ:
3322 	case SVM_VMGEXIT_MMIO_WRITE:
3323 		if (!kvm_ghcb_sw_scratch_is_valid(svm))
3324 			goto vmgexit_err;
3325 		break;
3326 	case SVM_VMGEXIT_AP_CREATION:
3327 		if (!sev_snp_guest(vcpu->kvm))
3328 			goto vmgexit_err;
3329 		if (lower_32_bits(control->exit_info_1) != SVM_VMGEXIT_AP_DESTROY)
3330 			if (!kvm_ghcb_rax_is_valid(svm))
3331 				goto vmgexit_err;
3332 		break;
3333 	case SVM_VMGEXIT_NMI_COMPLETE:
3334 	case SVM_VMGEXIT_AP_HLT_LOOP:
3335 	case SVM_VMGEXIT_AP_JUMP_TABLE:
3336 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
3337 	case SVM_VMGEXIT_HV_FEATURES:
3338 	case SVM_VMGEXIT_TERM_REQUEST:
3339 		break;
3340 	case SVM_VMGEXIT_PSC:
3341 		if (!sev_snp_guest(vcpu->kvm) || !kvm_ghcb_sw_scratch_is_valid(svm))
3342 			goto vmgexit_err;
3343 		break;
3344 	case SVM_VMGEXIT_GUEST_REQUEST:
3345 	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
3346 		if (!sev_snp_guest(vcpu->kvm) ||
3347 		    !PAGE_ALIGNED(control->exit_info_1) ||
3348 		    !PAGE_ALIGNED(control->exit_info_2) ||
3349 		    control->exit_info_1 == control->exit_info_2)
3350 			goto vmgexit_err;
3351 		break;
3352 	default:
3353 		reason = GHCB_ERR_INVALID_EVENT;
3354 		goto vmgexit_err;
3355 	}
3356 
3357 	return 0;
3358 
3359 vmgexit_err:
3360 	if (reason == GHCB_ERR_INVALID_USAGE) {
3361 		vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
3362 			    svm->sev_es.ghcb->ghcb_usage);
3363 	} else if (reason == GHCB_ERR_INVALID_EVENT) {
3364 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is not valid\n",
3365 			    exit_code);
3366 	} else {
3367 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx input is not valid\n",
3368 			    exit_code);
3369 		dump_ghcb(svm);
3370 	}
3371 
3372 	svm_vmgexit_bad_input(svm, reason);
3373 
3374 	/* Resume the guest to "return" the error code. */
3375 	return 1;
3376 }
3377 
3378 void sev_es_unmap_ghcb(struct vcpu_svm *svm)
3379 {
3380 	/* Clear any indication that the vCPU is in a type of AP Reset Hold */
3381 	svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NONE;
3382 
3383 	if (!svm->sev_es.ghcb)
3384 		return;
3385 
3386 	if (svm->sev_es.ghcb_sa_free) {
3387 		/*
3388 		 * The scratch area lives outside the GHCB, so there is a
3389 		 * buffer that, depending on the operation performed, may
3390 		 * need to be synced, then freed.
3391 		 */
3392 		if (svm->sev_es.ghcb_sa_sync) {
3393 			kvm_write_guest(svm->vcpu.kvm,
3394 					svm->sev_es.sw_scratch,
3395 					svm->sev_es.ghcb_sa,
3396 					svm->sev_es.ghcb_sa_len);
3397 			svm->sev_es.ghcb_sa_sync = false;
3398 		}
3399 
3400 		kvfree(svm->sev_es.ghcb_sa);
3401 		svm->sev_es.ghcb_sa = NULL;
3402 		svm->sev_es.ghcb_sa_free = false;
3403 	}
3404 
3405 	trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->sev_es.ghcb);
3406 
3407 	sev_es_sync_to_ghcb(svm);
3408 
3409 	kvm_vcpu_unmap(&svm->vcpu, &svm->sev_es.ghcb_map);
3410 	svm->sev_es.ghcb = NULL;
3411 }
3412 
3413 int pre_sev_run(struct vcpu_svm *svm, int cpu)
3414 {
3415 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
3416 	struct kvm *kvm = svm->vcpu.kvm;
3417 	unsigned int asid = sev_get_asid(kvm);
3418 
3419 	/*
3420 	 * Reject KVM_RUN if userspace attempts to run the vCPU with an invalid
3421 	 * VMSA, e.g. if userspace forces the vCPU to be RUNNABLE after an SNP
3422 	 * AP Destroy event.
3423 	 */
3424 	if (sev_es_guest(kvm) && !VALID_PAGE(svm->vmcb->control.vmsa_pa))
3425 		return -EINVAL;
3426 
3427 	/* Assign the asid allocated with this SEV guest */
3428 	svm->asid = asid;
3429 
3430 	/*
3431 	 * Flush guest TLB:
3432 	 *
3433 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
3434 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
3435 	 */
3436 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
3437 	    svm->vcpu.arch.last_vmentry_cpu == cpu)
3438 		return 0;
3439 
3440 	sd->sev_vmcbs[asid] = svm->vmcb;
3441 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3442 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3443 	return 0;
3444 }
3445 
3446 #define GHCB_SCRATCH_AREA_LIMIT		(16ULL * PAGE_SIZE)
3447 static int setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len)
3448 {
3449 	struct vmcb_control_area *control = &svm->vmcb->control;
3450 	u64 ghcb_scratch_beg, ghcb_scratch_end;
3451 	u64 scratch_gpa_beg, scratch_gpa_end;
3452 	void *scratch_va;
3453 
3454 	scratch_gpa_beg = svm->sev_es.sw_scratch;
3455 	if (!scratch_gpa_beg) {
3456 		pr_err("vmgexit: scratch gpa not provided\n");
3457 		goto e_scratch;
3458 	}
3459 
3460 	scratch_gpa_end = scratch_gpa_beg + len;
3461 	if (scratch_gpa_end < scratch_gpa_beg) {
3462 		pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
3463 		       len, scratch_gpa_beg);
3464 		goto e_scratch;
3465 	}
3466 
3467 	if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
3468 		/* Scratch area begins within GHCB */
3469 		ghcb_scratch_beg = control->ghcb_gpa +
3470 				   offsetof(struct ghcb, shared_buffer);
3471 		ghcb_scratch_end = control->ghcb_gpa +
3472 				   offsetof(struct ghcb, reserved_0xff0);
3473 
3474 		/*
3475 		 * If the scratch area begins within the GHCB, it must be
3476 		 * completely contained in the GHCB shared buffer area.
3477 		 */
3478 		if (scratch_gpa_beg < ghcb_scratch_beg ||
3479 		    scratch_gpa_end > ghcb_scratch_end) {
3480 			pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
3481 			       scratch_gpa_beg, scratch_gpa_end);
3482 			goto e_scratch;
3483 		}
3484 
3485 		scratch_va = (void *)svm->sev_es.ghcb;
3486 		scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
3487 	} else {
3488 		/*
3489 		 * The guest memory must be read into a kernel buffer, so
3490 		 * limit the size
3491 		 */
3492 		if (len > GHCB_SCRATCH_AREA_LIMIT) {
3493 			pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
3494 			       len, GHCB_SCRATCH_AREA_LIMIT);
3495 			goto e_scratch;
3496 		}
3497 		scratch_va = kvzalloc(len, GFP_KERNEL_ACCOUNT);
3498 		if (!scratch_va)
3499 			return -ENOMEM;
3500 
3501 		if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) {
3502 			/* Unable to copy scratch area from guest */
3503 			pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
3504 
3505 			kvfree(scratch_va);
3506 			return -EFAULT;
3507 		}
3508 
3509 		/*
3510 		 * The scratch area is outside the GHCB. The operation will
3511 		 * dictate whether the buffer needs to be synced before running
3512 		 * the vCPU next time (i.e. a read was requested so the data
3513 		 * must be written back to the guest memory).
3514 		 */
3515 		svm->sev_es.ghcb_sa_sync = sync;
3516 		svm->sev_es.ghcb_sa_free = true;
3517 	}
3518 
3519 	svm->sev_es.ghcb_sa = scratch_va;
3520 	svm->sev_es.ghcb_sa_len = len;
3521 
3522 	return 0;
3523 
3524 e_scratch:
3525 	svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_SCRATCH_AREA);
3526 
3527 	return 1;
3528 }
3529 
3530 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
3531 			      unsigned int pos)
3532 {
3533 	svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
3534 	svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
3535 }
3536 
3537 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
3538 {
3539 	return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
3540 }
3541 
3542 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
3543 {
3544 	svm->vmcb->control.ghcb_gpa = value;
3545 }
3546 
3547 static int snp_rmptable_psmash(kvm_pfn_t pfn)
3548 {
3549 	int ret;
3550 
3551 	pfn = pfn & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
3552 
3553 	/*
3554 	 * PSMASH_FAIL_INUSE indicates another processor is modifying the
3555 	 * entry, so retry until that's no longer the case.
3556 	 */
3557 	do {
3558 		ret = psmash(pfn);
3559 	} while (ret == PSMASH_FAIL_INUSE);
3560 
3561 	return ret;
3562 }
3563 
3564 static int snp_complete_psc_msr(struct kvm_vcpu *vcpu)
3565 {
3566 	struct vcpu_svm *svm = to_svm(vcpu);
3567 
3568 	if (vcpu->run->hypercall.ret)
3569 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3570 	else
3571 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP);
3572 
3573 	return 1; /* resume guest */
3574 }
3575 
3576 static int snp_begin_psc_msr(struct vcpu_svm *svm, u64 ghcb_msr)
3577 {
3578 	u64 gpa = gfn_to_gpa(GHCB_MSR_PSC_REQ_TO_GFN(ghcb_msr));
3579 	u8 op = GHCB_MSR_PSC_REQ_TO_OP(ghcb_msr);
3580 	struct kvm_vcpu *vcpu = &svm->vcpu;
3581 
3582 	if (op != SNP_PAGE_STATE_PRIVATE && op != SNP_PAGE_STATE_SHARED) {
3583 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3584 		return 1; /* resume guest */
3585 	}
3586 
3587 	if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) {
3588 		set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3589 		return 1; /* resume guest */
3590 	}
3591 
3592 	vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
3593 	vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
3594 	/*
3595 	 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
3596 	 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
3597 	 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
3598 	 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
3599 	 */
3600 	vcpu->run->hypercall.ret = 0;
3601 	vcpu->run->hypercall.args[0] = gpa;
3602 	vcpu->run->hypercall.args[1] = 1;
3603 	vcpu->run->hypercall.args[2] = (op == SNP_PAGE_STATE_PRIVATE)
3604 				       ? KVM_MAP_GPA_RANGE_ENCRYPTED
3605 				       : KVM_MAP_GPA_RANGE_DECRYPTED;
3606 	vcpu->run->hypercall.args[2] |= KVM_MAP_GPA_RANGE_PAGE_SZ_4K;
3607 
3608 	vcpu->arch.complete_userspace_io = snp_complete_psc_msr;
3609 
3610 	return 0; /* forward request to userspace */
3611 }
3612 
3613 struct psc_buffer {
3614 	struct psc_hdr hdr;
3615 	struct psc_entry entries[];
3616 } __packed;
3617 
3618 static int snp_begin_psc(struct vcpu_svm *svm, struct psc_buffer *psc);
3619 
3620 static void snp_complete_psc(struct vcpu_svm *svm, u64 psc_ret)
3621 {
3622 	svm->sev_es.psc_inflight = 0;
3623 	svm->sev_es.psc_idx = 0;
3624 	svm->sev_es.psc_2m = false;
3625 
3626 	/*
3627 	 * PSC requests always get a "no action" response in SW_EXITINFO1, with
3628 	 * a PSC-specific return code in SW_EXITINFO2 that provides the "real"
3629 	 * return code.  E.g. if the PSC request was interrupted, the need to
3630 	 * retry is communicated via SW_EXITINFO2, not SW_EXITINFO1.
3631 	 */
3632 	svm_vmgexit_no_action(svm, psc_ret);
3633 }
3634 
3635 static void __snp_complete_one_psc(struct vcpu_svm *svm)
3636 {
3637 	struct psc_buffer *psc = svm->sev_es.ghcb_sa;
3638 	struct psc_entry *entries = psc->entries;
3639 	struct psc_hdr *hdr = &psc->hdr;
3640 	__u16 idx;
3641 
3642 	/*
3643 	 * Everything in-flight has been processed successfully. Update the
3644 	 * corresponding entries in the guest's PSC buffer and zero out the
3645 	 * count of in-flight PSC entries.
3646 	 */
3647 	for (idx = svm->sev_es.psc_idx; svm->sev_es.psc_inflight;
3648 	     svm->sev_es.psc_inflight--, idx++) {
3649 		struct psc_entry *entry = &entries[idx];
3650 
3651 		entry->cur_page = entry->pagesize ? 512 : 1;
3652 	}
3653 
3654 	hdr->cur_entry = idx;
3655 }
3656 
3657 static int snp_complete_one_psc(struct kvm_vcpu *vcpu)
3658 {
3659 	struct vcpu_svm *svm = to_svm(vcpu);
3660 	struct psc_buffer *psc = svm->sev_es.ghcb_sa;
3661 
3662 	if (vcpu->run->hypercall.ret) {
3663 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3664 		return 1; /* resume guest */
3665 	}
3666 
3667 	__snp_complete_one_psc(svm);
3668 
3669 	/* Handle the next range (if any). */
3670 	return snp_begin_psc(svm, psc);
3671 }
3672 
3673 static int snp_begin_psc(struct vcpu_svm *svm, struct psc_buffer *psc)
3674 {
3675 	struct psc_entry *entries = psc->entries;
3676 	struct kvm_vcpu *vcpu = &svm->vcpu;
3677 	struct psc_hdr *hdr = &psc->hdr;
3678 	struct psc_entry entry_start;
3679 	u16 idx, idx_start, idx_end;
3680 	int npages;
3681 	bool huge;
3682 	u64 gfn;
3683 
3684 	if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) {
3685 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3686 		return 1;
3687 	}
3688 
3689 next_range:
3690 	/* There should be no other PSCs in-flight at this point. */
3691 	if (WARN_ON_ONCE(svm->sev_es.psc_inflight)) {
3692 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3693 		return 1;
3694 	}
3695 
3696 	/*
3697 	 * The PSC descriptor buffer can be modified by a misbehaved guest after
3698 	 * validation, so take care to only use validated copies of values used
3699 	 * for things like array indexing.
3700 	 */
3701 	idx_start = hdr->cur_entry;
3702 	idx_end = hdr->end_entry;
3703 
3704 	if (idx_end >= VMGEXIT_PSC_MAX_COUNT) {
3705 		snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_HDR);
3706 		return 1;
3707 	}
3708 
3709 	/* Find the start of the next range which needs processing. */
3710 	for (idx = idx_start; idx <= idx_end; idx++, hdr->cur_entry++) {
3711 		entry_start = entries[idx];
3712 
3713 		gfn = entry_start.gfn;
3714 		huge = entry_start.pagesize;
3715 		npages = huge ? 512 : 1;
3716 
3717 		if (entry_start.cur_page > npages || !IS_ALIGNED(gfn, npages)) {
3718 			snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_ENTRY);
3719 			return 1;
3720 		}
3721 
3722 		if (entry_start.cur_page) {
3723 			/*
3724 			 * If this is a partially-completed 2M range, force 4K handling
3725 			 * for the remaining pages since they're effectively split at
3726 			 * this point. Subsequent code should ensure this doesn't get
3727 			 * combined with adjacent PSC entries where 2M handling is still
3728 			 * possible.
3729 			 */
3730 			npages -= entry_start.cur_page;
3731 			gfn += entry_start.cur_page;
3732 			huge = false;
3733 		}
3734 
3735 		if (npages)
3736 			break;
3737 	}
3738 
3739 	if (idx > idx_end) {
3740 		/* Nothing more to process. */
3741 		snp_complete_psc(svm, 0);
3742 		return 1;
3743 	}
3744 
3745 	svm->sev_es.psc_2m = huge;
3746 	svm->sev_es.psc_idx = idx;
3747 	svm->sev_es.psc_inflight = 1;
3748 
3749 	/*
3750 	 * Find all subsequent PSC entries that contain adjacent GPA
3751 	 * ranges/operations and can be combined into a single
3752 	 * KVM_HC_MAP_GPA_RANGE exit.
3753 	 */
3754 	while (++idx <= idx_end) {
3755 		struct psc_entry entry = entries[idx];
3756 
3757 		if (entry.operation != entry_start.operation ||
3758 		    entry.gfn != entry_start.gfn + npages ||
3759 		    entry.cur_page || !!entry.pagesize != huge)
3760 			break;
3761 
3762 		svm->sev_es.psc_inflight++;
3763 		npages += huge ? 512 : 1;
3764 	}
3765 
3766 	switch (entry_start.operation) {
3767 	case VMGEXIT_PSC_OP_PRIVATE:
3768 	case VMGEXIT_PSC_OP_SHARED:
3769 		vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
3770 		vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
3771 		/*
3772 		 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
3773 		 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
3774 		 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
3775 		 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
3776 		 */
3777 		vcpu->run->hypercall.ret = 0;
3778 		vcpu->run->hypercall.args[0] = gfn_to_gpa(gfn);
3779 		vcpu->run->hypercall.args[1] = npages;
3780 		vcpu->run->hypercall.args[2] = entry_start.operation == VMGEXIT_PSC_OP_PRIVATE
3781 					       ? KVM_MAP_GPA_RANGE_ENCRYPTED
3782 					       : KVM_MAP_GPA_RANGE_DECRYPTED;
3783 		vcpu->run->hypercall.args[2] |= entry_start.pagesize
3784 						? KVM_MAP_GPA_RANGE_PAGE_SZ_2M
3785 						: KVM_MAP_GPA_RANGE_PAGE_SZ_4K;
3786 		vcpu->arch.complete_userspace_io = snp_complete_one_psc;
3787 		return 0; /* forward request to userspace */
3788 	default:
3789 		/*
3790 		 * Only shared/private PSC operations are currently supported, so if the
3791 		 * entire range consists of unsupported operations (e.g. SMASH/UNSMASH),
3792 		 * then consider the entire range completed and avoid exiting to
3793 		 * userspace. In theory snp_complete_psc() can always be called directly
3794 		 * at this point to complete the current range and start the next one,
3795 		 * but that could lead to unexpected levels of recursion.
3796 		 */
3797 		__snp_complete_one_psc(svm);
3798 		goto next_range;
3799 	}
3800 
3801 	BUG();
3802 }
3803 
3804 /*
3805  * Invoked as part of svm_vcpu_reset() processing of an init event.
3806  */
3807 void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu)
3808 {
3809 	struct vcpu_svm *svm = to_svm(vcpu);
3810 	struct kvm_memory_slot *slot;
3811 	struct page *page;
3812 	kvm_pfn_t pfn;
3813 	gfn_t gfn;
3814 
3815 	if (!sev_snp_guest(vcpu->kvm))
3816 		return;
3817 
3818 	guard(mutex)(&svm->sev_es.snp_vmsa_mutex);
3819 
3820 	if (!svm->sev_es.snp_ap_waiting_for_reset)
3821 		return;
3822 
3823 	svm->sev_es.snp_ap_waiting_for_reset = false;
3824 
3825 	/* Mark the vCPU as offline and not runnable */
3826 	vcpu->arch.pv.pv_unhalted = false;
3827 	kvm_set_mp_state(vcpu, KVM_MP_STATE_HALTED);
3828 
3829 	/* Clear use of the VMSA */
3830 	svm->vmcb->control.vmsa_pa = INVALID_PAGE;
3831 
3832 	/*
3833 	 * When replacing the VMSA during SEV-SNP AP creation,
3834 	 * mark the VMCB dirty so that full state is always reloaded.
3835 	 */
3836 	vmcb_mark_all_dirty(svm->vmcb);
3837 
3838 	if (!VALID_PAGE(svm->sev_es.snp_vmsa_gpa))
3839 		return;
3840 
3841 	gfn = gpa_to_gfn(svm->sev_es.snp_vmsa_gpa);
3842 	svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
3843 
3844 	slot = gfn_to_memslot(vcpu->kvm, gfn);
3845 	if (!slot)
3846 		return;
3847 
3848 	/*
3849 	 * The new VMSA will be private memory guest memory, so retrieve the
3850 	 * PFN from the gmem backend.
3851 	 */
3852 	if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL))
3853 		return;
3854 
3855 	/*
3856 	 * From this point forward, the VMSA will always be a guest-mapped page
3857 	 * rather than the initial one allocated by KVM in svm->sev_es.vmsa. In
3858 	 * theory, svm->sev_es.vmsa could be free'd and cleaned up here, but
3859 	 * that involves cleanups like wbinvd_on_all_cpus() which would ideally
3860 	 * be handled during teardown rather than guest boot.  Deferring that
3861 	 * also allows the existing logic for SEV-ES VMSAs to be re-used with
3862 	 * minimal SNP-specific changes.
3863 	 */
3864 	svm->sev_es.snp_has_guest_vmsa = true;
3865 
3866 	/* Use the new VMSA */
3867 	svm->vmcb->control.vmsa_pa = pfn_to_hpa(pfn);
3868 
3869 	/* Mark the vCPU as runnable */
3870 	kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
3871 
3872 	/*
3873 	 * gmem pages aren't currently migratable, but if this ever changes
3874 	 * then care should be taken to ensure svm->sev_es.vmsa is pinned
3875 	 * through some other means.
3876 	 */
3877 	kvm_release_page_clean(page);
3878 }
3879 
3880 static int sev_snp_ap_creation(struct vcpu_svm *svm)
3881 {
3882 	struct kvm_sev_info *sev = to_kvm_sev_info(svm->vcpu.kvm);
3883 	struct kvm_vcpu *vcpu = &svm->vcpu;
3884 	struct kvm_vcpu *target_vcpu;
3885 	struct vcpu_svm *target_svm;
3886 	unsigned int request;
3887 	unsigned int apic_id;
3888 
3889 	request = lower_32_bits(svm->vmcb->control.exit_info_1);
3890 	apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
3891 
3892 	/* Validate the APIC ID */
3893 	target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);
3894 	if (!target_vcpu) {
3895 		vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
3896 			    apic_id);
3897 		return -EINVAL;
3898 	}
3899 
3900 	target_svm = to_svm(target_vcpu);
3901 
3902 	guard(mutex)(&target_svm->sev_es.snp_vmsa_mutex);
3903 
3904 	switch (request) {
3905 	case SVM_VMGEXIT_AP_CREATE_ON_INIT:
3906 	case SVM_VMGEXIT_AP_CREATE:
3907 		if (vcpu->arch.regs[VCPU_REGS_RAX] != sev->vmsa_features) {
3908 			vcpu_unimpl(vcpu, "vmgexit: mismatched AP sev_features [%#lx] != [%#llx] from guest\n",
3909 				    vcpu->arch.regs[VCPU_REGS_RAX], sev->vmsa_features);
3910 			return -EINVAL;
3911 		}
3912 
3913 		if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
3914 			vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
3915 				    svm->vmcb->control.exit_info_2);
3916 			return -EINVAL;
3917 		}
3918 
3919 		/*
3920 		 * Malicious guest can RMPADJUST a large page into VMSA which
3921 		 * will hit the SNP erratum where the CPU will incorrectly signal
3922 		 * an RMP violation #PF if a hugepage collides with the RMP entry
3923 		 * of VMSA page, reject the AP CREATE request if VMSA address from
3924 		 * guest is 2M aligned.
3925 		 */
3926 		if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
3927 			vcpu_unimpl(vcpu,
3928 				    "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
3929 				    svm->vmcb->control.exit_info_2);
3930 			return -EINVAL;
3931 		}
3932 
3933 		target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2;
3934 		break;
3935 	case SVM_VMGEXIT_AP_DESTROY:
3936 		target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
3937 		break;
3938 	default:
3939 		vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
3940 			    request);
3941 		return -EINVAL;
3942 	}
3943 
3944 	target_svm->sev_es.snp_ap_waiting_for_reset = true;
3945 
3946 	/*
3947 	 * Unless Creation is deferred until INIT, signal the vCPU to update
3948 	 * its state.
3949 	 */
3950 	if (request != SVM_VMGEXIT_AP_CREATE_ON_INIT)
3951 		kvm_make_request_and_kick(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
3952 
3953 	return 0;
3954 }
3955 
3956 static int snp_handle_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
3957 {
3958 	struct sev_data_snp_guest_request data = {0};
3959 	struct kvm *kvm = svm->vcpu.kvm;
3960 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
3961 	sev_ret_code fw_err = 0;
3962 	int ret;
3963 
3964 	if (!sev_snp_guest(kvm))
3965 		return -EINVAL;
3966 
3967 	mutex_lock(&sev->guest_req_mutex);
3968 
3969 	if (kvm_read_guest(kvm, req_gpa, sev->guest_req_buf, PAGE_SIZE)) {
3970 		ret = -EIO;
3971 		goto out_unlock;
3972 	}
3973 
3974 	data.gctx_paddr = __psp_pa(sev->snp_context);
3975 	data.req_paddr = __psp_pa(sev->guest_req_buf);
3976 	data.res_paddr = __psp_pa(sev->guest_resp_buf);
3977 
3978 	/*
3979 	 * Firmware failures are propagated on to guest, but any other failure
3980 	 * condition along the way should be reported to userspace. E.g. if
3981 	 * the PSP is dead and commands are timing out.
3982 	 */
3983 	ret = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &fw_err);
3984 	if (ret && !fw_err)
3985 		goto out_unlock;
3986 
3987 	if (kvm_write_guest(kvm, resp_gpa, sev->guest_resp_buf, PAGE_SIZE)) {
3988 		ret = -EIO;
3989 		goto out_unlock;
3990 	}
3991 
3992 	/* No action is requested *from KVM* if there was a firmware error. */
3993 	svm_vmgexit_no_action(svm, SNP_GUEST_ERR(0, fw_err));
3994 
3995 	ret = 1; /* resume guest */
3996 
3997 out_unlock:
3998 	mutex_unlock(&sev->guest_req_mutex);
3999 	return ret;
4000 }
4001 
4002 static int snp_handle_ext_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
4003 {
4004 	struct kvm *kvm = svm->vcpu.kvm;
4005 	u8 msg_type;
4006 
4007 	if (!sev_snp_guest(kvm))
4008 		return -EINVAL;
4009 
4010 	if (kvm_read_guest(kvm, req_gpa + offsetof(struct snp_guest_msg_hdr, msg_type),
4011 			   &msg_type, 1))
4012 		return -EIO;
4013 
4014 	/*
4015 	 * As per GHCB spec, requests of type MSG_REPORT_REQ also allow for
4016 	 * additional certificate data to be provided alongside the attestation
4017 	 * report via the guest-provided data pages indicated by RAX/RBX. The
4018 	 * certificate data is optional and requires additional KVM enablement
4019 	 * to provide an interface for userspace to provide it, but KVM still
4020 	 * needs to be able to handle extended guest requests either way. So
4021 	 * provide a stub implementation that will always return an empty
4022 	 * certificate table in the guest-provided data pages.
4023 	 */
4024 	if (msg_type == SNP_MSG_REPORT_REQ) {
4025 		struct kvm_vcpu *vcpu = &svm->vcpu;
4026 		u64 data_npages;
4027 		gpa_t data_gpa;
4028 
4029 		if (!kvm_ghcb_rax_is_valid(svm) || !kvm_ghcb_rbx_is_valid(svm))
4030 			goto request_invalid;
4031 
4032 		data_gpa = vcpu->arch.regs[VCPU_REGS_RAX];
4033 		data_npages = vcpu->arch.regs[VCPU_REGS_RBX];
4034 
4035 		if (!PAGE_ALIGNED(data_gpa))
4036 			goto request_invalid;
4037 
4038 		/*
4039 		 * As per GHCB spec (see "SNP Extended Guest Request"), the
4040 		 * certificate table is terminated by 24-bytes of zeroes.
4041 		 */
4042 		if (data_npages && kvm_clear_guest(kvm, data_gpa, 24))
4043 			return -EIO;
4044 	}
4045 
4046 	return snp_handle_guest_req(svm, req_gpa, resp_gpa);
4047 
4048 request_invalid:
4049 	svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4050 	return 1; /* resume guest */
4051 }
4052 
4053 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
4054 {
4055 	struct vmcb_control_area *control = &svm->vmcb->control;
4056 	struct kvm_vcpu *vcpu = &svm->vcpu;
4057 	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
4058 	u64 ghcb_info;
4059 	int ret = 1;
4060 
4061 	ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
4062 
4063 	trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
4064 					     control->ghcb_gpa);
4065 
4066 	switch (ghcb_info) {
4067 	case GHCB_MSR_SEV_INFO_REQ:
4068 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version,
4069 						    GHCB_VERSION_MIN,
4070 						    sev_enc_bit));
4071 		break;
4072 	case GHCB_MSR_CPUID_REQ: {
4073 		u64 cpuid_fn, cpuid_reg, cpuid_value;
4074 
4075 		cpuid_fn = get_ghcb_msr_bits(svm,
4076 					     GHCB_MSR_CPUID_FUNC_MASK,
4077 					     GHCB_MSR_CPUID_FUNC_POS);
4078 
4079 		/* Initialize the registers needed by the CPUID intercept */
4080 		vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
4081 		vcpu->arch.regs[VCPU_REGS_RCX] = 0;
4082 
4083 		ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
4084 		if (!ret) {
4085 			/* Error, keep GHCB MSR value as-is */
4086 			break;
4087 		}
4088 
4089 		cpuid_reg = get_ghcb_msr_bits(svm,
4090 					      GHCB_MSR_CPUID_REG_MASK,
4091 					      GHCB_MSR_CPUID_REG_POS);
4092 		if (cpuid_reg == 0)
4093 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
4094 		else if (cpuid_reg == 1)
4095 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
4096 		else if (cpuid_reg == 2)
4097 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
4098 		else
4099 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
4100 
4101 		set_ghcb_msr_bits(svm, cpuid_value,
4102 				  GHCB_MSR_CPUID_VALUE_MASK,
4103 				  GHCB_MSR_CPUID_VALUE_POS);
4104 
4105 		set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
4106 				  GHCB_MSR_INFO_MASK,
4107 				  GHCB_MSR_INFO_POS);
4108 		break;
4109 	}
4110 	case GHCB_MSR_AP_RESET_HOLD_REQ:
4111 		svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_MSR_PROTO;
4112 		ret = kvm_emulate_ap_reset_hold(&svm->vcpu);
4113 
4114 		/*
4115 		 * Preset the result to a non-SIPI return and then only set
4116 		 * the result to non-zero when delivering a SIPI.
4117 		 */
4118 		set_ghcb_msr_bits(svm, 0,
4119 				  GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,
4120 				  GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
4121 
4122 		set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP,
4123 				  GHCB_MSR_INFO_MASK,
4124 				  GHCB_MSR_INFO_POS);
4125 		break;
4126 	case GHCB_MSR_HV_FT_REQ:
4127 		set_ghcb_msr_bits(svm, GHCB_HV_FT_SUPPORTED,
4128 				  GHCB_MSR_HV_FT_MASK, GHCB_MSR_HV_FT_POS);
4129 		set_ghcb_msr_bits(svm, GHCB_MSR_HV_FT_RESP,
4130 				  GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
4131 		break;
4132 	case GHCB_MSR_PREF_GPA_REQ:
4133 		if (!sev_snp_guest(vcpu->kvm))
4134 			goto out_terminate;
4135 
4136 		set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_NONE, GHCB_MSR_GPA_VALUE_MASK,
4137 				  GHCB_MSR_GPA_VALUE_POS);
4138 		set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_RESP, GHCB_MSR_INFO_MASK,
4139 				  GHCB_MSR_INFO_POS);
4140 		break;
4141 	case GHCB_MSR_REG_GPA_REQ: {
4142 		u64 gfn;
4143 
4144 		if (!sev_snp_guest(vcpu->kvm))
4145 			goto out_terminate;
4146 
4147 		gfn = get_ghcb_msr_bits(svm, GHCB_MSR_GPA_VALUE_MASK,
4148 					GHCB_MSR_GPA_VALUE_POS);
4149 
4150 		svm->sev_es.ghcb_registered_gpa = gfn_to_gpa(gfn);
4151 
4152 		set_ghcb_msr_bits(svm, gfn, GHCB_MSR_GPA_VALUE_MASK,
4153 				  GHCB_MSR_GPA_VALUE_POS);
4154 		set_ghcb_msr_bits(svm, GHCB_MSR_REG_GPA_RESP, GHCB_MSR_INFO_MASK,
4155 				  GHCB_MSR_INFO_POS);
4156 		break;
4157 	}
4158 	case GHCB_MSR_PSC_REQ:
4159 		if (!sev_snp_guest(vcpu->kvm))
4160 			goto out_terminate;
4161 
4162 		ret = snp_begin_psc_msr(svm, control->ghcb_gpa);
4163 		break;
4164 	case GHCB_MSR_TERM_REQ: {
4165 		u64 reason_set, reason_code;
4166 
4167 		reason_set = get_ghcb_msr_bits(svm,
4168 					       GHCB_MSR_TERM_REASON_SET_MASK,
4169 					       GHCB_MSR_TERM_REASON_SET_POS);
4170 		reason_code = get_ghcb_msr_bits(svm,
4171 						GHCB_MSR_TERM_REASON_MASK,
4172 						GHCB_MSR_TERM_REASON_POS);
4173 		pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
4174 			reason_set, reason_code);
4175 
4176 		goto out_terminate;
4177 	}
4178 	default:
4179 		/* Error, keep GHCB MSR value as-is */
4180 		break;
4181 	}
4182 
4183 	trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
4184 					    control->ghcb_gpa, ret);
4185 
4186 	return ret;
4187 
4188 out_terminate:
4189 	vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
4190 	vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
4191 	vcpu->run->system_event.ndata = 1;
4192 	vcpu->run->system_event.data[0] = control->ghcb_gpa;
4193 
4194 	return 0;
4195 }
4196 
4197 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
4198 {
4199 	struct vcpu_svm *svm = to_svm(vcpu);
4200 	struct vmcb_control_area *control = &svm->vmcb->control;
4201 	u64 ghcb_gpa, exit_code;
4202 	int ret;
4203 
4204 	/* Validate the GHCB */
4205 	ghcb_gpa = control->ghcb_gpa;
4206 	if (ghcb_gpa & GHCB_MSR_INFO_MASK)
4207 		return sev_handle_vmgexit_msr_protocol(svm);
4208 
4209 	if (!ghcb_gpa) {
4210 		vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n");
4211 
4212 		/* Without a GHCB, just return right back to the guest */
4213 		return 1;
4214 	}
4215 
4216 	if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->sev_es.ghcb_map)) {
4217 		/* Unable to map GHCB from guest */
4218 		vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
4219 			    ghcb_gpa);
4220 
4221 		/* Without a GHCB, just return right back to the guest */
4222 		return 1;
4223 	}
4224 
4225 	svm->sev_es.ghcb = svm->sev_es.ghcb_map.hva;
4226 
4227 	trace_kvm_vmgexit_enter(vcpu->vcpu_id, svm->sev_es.ghcb);
4228 
4229 	sev_es_sync_from_ghcb(svm);
4230 
4231 	/* SEV-SNP guest requires that the GHCB GPA must be registered */
4232 	if (sev_snp_guest(svm->vcpu.kvm) && !ghcb_gpa_is_registered(svm, ghcb_gpa)) {
4233 		vcpu_unimpl(&svm->vcpu, "vmgexit: GHCB GPA [%#llx] is not registered.\n", ghcb_gpa);
4234 		return -EINVAL;
4235 	}
4236 
4237 	ret = sev_es_validate_vmgexit(svm);
4238 	if (ret)
4239 		return ret;
4240 
4241 	svm_vmgexit_success(svm, 0);
4242 
4243 	exit_code = kvm_ghcb_get_sw_exit_code(control);
4244 	switch (exit_code) {
4245 	case SVM_VMGEXIT_MMIO_READ:
4246 		ret = setup_vmgexit_scratch(svm, true, control->exit_info_2);
4247 		if (ret)
4248 			break;
4249 
4250 		ret = kvm_sev_es_mmio_read(vcpu,
4251 					   control->exit_info_1,
4252 					   control->exit_info_2,
4253 					   svm->sev_es.ghcb_sa);
4254 		break;
4255 	case SVM_VMGEXIT_MMIO_WRITE:
4256 		ret = setup_vmgexit_scratch(svm, false, control->exit_info_2);
4257 		if (ret)
4258 			break;
4259 
4260 		ret = kvm_sev_es_mmio_write(vcpu,
4261 					    control->exit_info_1,
4262 					    control->exit_info_2,
4263 					    svm->sev_es.ghcb_sa);
4264 		break;
4265 	case SVM_VMGEXIT_NMI_COMPLETE:
4266 		++vcpu->stat.nmi_window_exits;
4267 		svm->nmi_masked = false;
4268 		kvm_make_request(KVM_REQ_EVENT, vcpu);
4269 		ret = 1;
4270 		break;
4271 	case SVM_VMGEXIT_AP_HLT_LOOP:
4272 		svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NAE_EVENT;
4273 		ret = kvm_emulate_ap_reset_hold(vcpu);
4274 		break;
4275 	case SVM_VMGEXIT_AP_JUMP_TABLE: {
4276 		struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
4277 
4278 		switch (control->exit_info_1) {
4279 		case 0:
4280 			/* Set AP jump table address */
4281 			sev->ap_jump_table = control->exit_info_2;
4282 			break;
4283 		case 1:
4284 			/* Get AP jump table address */
4285 			svm_vmgexit_success(svm, sev->ap_jump_table);
4286 			break;
4287 		default:
4288 			pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
4289 			       control->exit_info_1);
4290 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4291 		}
4292 
4293 		ret = 1;
4294 		break;
4295 	}
4296 	case SVM_VMGEXIT_HV_FEATURES:
4297 		svm_vmgexit_success(svm, GHCB_HV_FT_SUPPORTED);
4298 		ret = 1;
4299 		break;
4300 	case SVM_VMGEXIT_TERM_REQUEST:
4301 		pr_info("SEV-ES guest requested termination: reason %#llx info %#llx\n",
4302 			control->exit_info_1, control->exit_info_2);
4303 		vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
4304 		vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
4305 		vcpu->run->system_event.ndata = 1;
4306 		vcpu->run->system_event.data[0] = control->ghcb_gpa;
4307 		break;
4308 	case SVM_VMGEXIT_PSC:
4309 		ret = setup_vmgexit_scratch(svm, true, control->exit_info_2);
4310 		if (ret)
4311 			break;
4312 
4313 		ret = snp_begin_psc(svm, svm->sev_es.ghcb_sa);
4314 		break;
4315 	case SVM_VMGEXIT_AP_CREATION:
4316 		ret = sev_snp_ap_creation(svm);
4317 		if (ret) {
4318 			svm_vmgexit_bad_input(svm, GHCB_ERR_INVALID_INPUT);
4319 		}
4320 
4321 		ret = 1;
4322 		break;
4323 	case SVM_VMGEXIT_GUEST_REQUEST:
4324 		ret = snp_handle_guest_req(svm, control->exit_info_1, control->exit_info_2);
4325 		break;
4326 	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
4327 		ret = snp_handle_ext_guest_req(svm, control->exit_info_1, control->exit_info_2);
4328 		break;
4329 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
4330 		vcpu_unimpl(vcpu,
4331 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
4332 			    control->exit_info_1, control->exit_info_2);
4333 		ret = -EINVAL;
4334 		break;
4335 	default:
4336 		ret = svm_invoke_exit_handler(vcpu, exit_code);
4337 	}
4338 
4339 	return ret;
4340 }
4341 
4342 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
4343 {
4344 	int count;
4345 	int bytes;
4346 	int r;
4347 
4348 	if (svm->vmcb->control.exit_info_2 > INT_MAX)
4349 		return -EINVAL;
4350 
4351 	count = svm->vmcb->control.exit_info_2;
4352 	if (unlikely(check_mul_overflow(count, size, &bytes)))
4353 		return -EINVAL;
4354 
4355 	r = setup_vmgexit_scratch(svm, in, bytes);
4356 	if (r)
4357 		return r;
4358 
4359 	return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->sev_es.ghcb_sa,
4360 				    count, in);
4361 }
4362 
4363 static void sev_es_vcpu_after_set_cpuid(struct vcpu_svm *svm)
4364 {
4365 	struct kvm_vcpu *vcpu = &svm->vcpu;
4366 
4367 	if (boot_cpu_has(X86_FEATURE_V_TSC_AUX)) {
4368 		bool v_tsc_aux = guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) ||
4369 				 guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID);
4370 
4371 		set_msr_interception(vcpu, svm->msrpm, MSR_TSC_AUX, v_tsc_aux, v_tsc_aux);
4372 	}
4373 
4374 	/*
4375 	 * For SEV-ES, accesses to MSR_IA32_XSS should not be intercepted if
4376 	 * the host/guest supports its use.
4377 	 *
4378 	 * KVM treats the guest as being capable of using XSAVES even if XSAVES
4379 	 * isn't enabled in guest CPUID as there is no intercept for XSAVES,
4380 	 * i.e. the guest can use XSAVES/XRSTOR to read/write XSS if XSAVE is
4381 	 * exposed to the guest and XSAVES is supported in hardware.  Condition
4382 	 * full XSS passthrough on the guest being able to use XSAVES *and*
4383 	 * XSAVES being exposed to the guest so that KVM can at least honor
4384 	 * guest CPUID for RDMSR and WRMSR.
4385 	 */
4386 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
4387 	    guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4388 		set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 1, 1);
4389 	else
4390 		set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 0, 0);
4391 }
4392 
4393 void sev_vcpu_after_set_cpuid(struct vcpu_svm *svm)
4394 {
4395 	struct kvm_vcpu *vcpu = &svm->vcpu;
4396 	struct kvm_cpuid_entry2 *best;
4397 
4398 	/* For sev guests, the memory encryption bit is not reserved in CR3.  */
4399 	best = kvm_find_cpuid_entry(vcpu, 0x8000001F);
4400 	if (best)
4401 		vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4402 
4403 	if (sev_es_guest(svm->vcpu.kvm))
4404 		sev_es_vcpu_after_set_cpuid(svm);
4405 }
4406 
4407 static void sev_es_init_vmcb(struct vcpu_svm *svm)
4408 {
4409 	struct kvm_sev_info *sev = to_kvm_sev_info(svm->vcpu.kvm);
4410 	struct vmcb *vmcb = svm->vmcb01.ptr;
4411 	struct kvm_vcpu *vcpu = &svm->vcpu;
4412 
4413 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE;
4414 
4415 	/*
4416 	 * An SEV-ES guest requires a VMSA area that is a separate from the
4417 	 * VMCB page. Do not include the encryption mask on the VMSA physical
4418 	 * address since hardware will access it using the guest key.  Note,
4419 	 * the VMSA will be NULL if this vCPU is the destination for intrahost
4420 	 * migration, and will be copied later.
4421 	 */
4422 	if (svm->sev_es.vmsa && !svm->sev_es.snp_has_guest_vmsa)
4423 		svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa);
4424 
4425 	if (cpu_feature_enabled(X86_FEATURE_ALLOWED_SEV_FEATURES))
4426 		svm->vmcb->control.allowed_sev_features = sev->vmsa_features |
4427 							  VMCB_ALLOWED_SEV_FEATURES_VALID;
4428 
4429 	/* Can't intercept CR register access, HV can't modify CR registers */
4430 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
4431 	svm_clr_intercept(svm, INTERCEPT_CR4_READ);
4432 	svm_clr_intercept(svm, INTERCEPT_CR8_READ);
4433 	svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
4434 	svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
4435 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
4436 
4437 	svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
4438 
4439 	/* Track EFER/CR register changes */
4440 	svm_set_intercept(svm, TRAP_EFER_WRITE);
4441 	svm_set_intercept(svm, TRAP_CR0_WRITE);
4442 	svm_set_intercept(svm, TRAP_CR4_WRITE);
4443 	svm_set_intercept(svm, TRAP_CR8_WRITE);
4444 
4445 	vmcb->control.intercepts[INTERCEPT_DR] = 0;
4446 	if (!sev_vcpu_has_debug_swap(svm)) {
4447 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
4448 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
4449 		recalc_intercepts(svm);
4450 	} else {
4451 		/*
4452 		 * Disable #DB intercept iff DebugSwap is enabled.  KVM doesn't
4453 		 * allow debugging SEV-ES guests, and enables DebugSwap iff
4454 		 * NO_NESTED_DATA_BP is supported, so there's no reason to
4455 		 * intercept #DB when DebugSwap is enabled.  For simplicity
4456 		 * with respect to guest debug, intercept #DB for other VMs
4457 		 * even if NO_NESTED_DATA_BP is supported, i.e. even if the
4458 		 * guest can't DoS the CPU with infinite #DB vectoring.
4459 		 */
4460 		clr_exception_intercept(svm, DB_VECTOR);
4461 	}
4462 
4463 	/* Can't intercept XSETBV, HV can't modify XCR0 directly */
4464 	svm_clr_intercept(svm, INTERCEPT_XSETBV);
4465 
4466 	/* Clear intercepts on selected MSRs */
4467 	set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1);
4468 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1);
4469 }
4470 
4471 void sev_init_vmcb(struct vcpu_svm *svm)
4472 {
4473 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
4474 	clr_exception_intercept(svm, UD_VECTOR);
4475 
4476 	/*
4477 	 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as
4478 	 * KVM can't decrypt guest memory to decode the faulting instruction.
4479 	 */
4480 	clr_exception_intercept(svm, GP_VECTOR);
4481 
4482 	if (sev_es_guest(svm->vcpu.kvm))
4483 		sev_es_init_vmcb(svm);
4484 }
4485 
4486 void sev_es_vcpu_reset(struct vcpu_svm *svm)
4487 {
4488 	struct kvm_vcpu *vcpu = &svm->vcpu;
4489 	struct kvm_sev_info *sev = to_kvm_sev_info(vcpu->kvm);
4490 
4491 	/*
4492 	 * Set the GHCB MSR value as per the GHCB specification when emulating
4493 	 * vCPU RESET for an SEV-ES guest.
4494 	 */
4495 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version,
4496 					    GHCB_VERSION_MIN,
4497 					    sev_enc_bit));
4498 
4499 	mutex_init(&svm->sev_es.snp_vmsa_mutex);
4500 }
4501 
4502 void sev_es_prepare_switch_to_guest(struct vcpu_svm *svm, struct sev_es_save_area *hostsa)
4503 {
4504 	struct kvm *kvm = svm->vcpu.kvm;
4505 
4506 	/*
4507 	 * All host state for SEV-ES guests is categorized into three swap types
4508 	 * based on how it is handled by hardware during a world switch:
4509 	 *
4510 	 * A: VMRUN:   Host state saved in host save area
4511 	 *    VMEXIT:  Host state loaded from host save area
4512 	 *
4513 	 * B: VMRUN:   Host state _NOT_ saved in host save area
4514 	 *    VMEXIT:  Host state loaded from host save area
4515 	 *
4516 	 * C: VMRUN:   Host state _NOT_ saved in host save area
4517 	 *    VMEXIT:  Host state initialized to default(reset) values
4518 	 *
4519 	 * Manually save type-B state, i.e. state that is loaded by VMEXIT but
4520 	 * isn't saved by VMRUN, that isn't already saved by VMSAVE (performed
4521 	 * by common SVM code).
4522 	 */
4523 	hostsa->xcr0 = kvm_host.xcr0;
4524 	hostsa->pkru = read_pkru();
4525 	hostsa->xss = kvm_host.xss;
4526 
4527 	/*
4528 	 * If DebugSwap is enabled, debug registers are loaded but NOT saved by
4529 	 * the CPU (Type-B). If DebugSwap is disabled/unsupported, the CPU does
4530 	 * not save or load debug registers.  Sadly, KVM can't prevent SNP
4531 	 * guests from lying about DebugSwap on secondary vCPUs, i.e. the
4532 	 * SEV_FEATURES provided at "AP Create" isn't guaranteed to match what
4533 	 * the guest has actually enabled (or not!) in the VMSA.
4534 	 *
4535 	 * If DebugSwap is *possible*, save the masks so that they're restored
4536 	 * if the guest enables DebugSwap.  But for the DRs themselves, do NOT
4537 	 * rely on the CPU to restore the host values; KVM will restore them as
4538 	 * needed in common code, via hw_breakpoint_restore().  Note, KVM does
4539 	 * NOT support virtualizing Breakpoint Extensions, i.e. the mask MSRs
4540 	 * don't need to be restored per se, KVM just needs to ensure they are
4541 	 * loaded with the correct values *if* the CPU writes the MSRs.
4542 	 */
4543 	if (sev_vcpu_has_debug_swap(svm) ||
4544 	    (sev_snp_guest(kvm) && cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP))) {
4545 		hostsa->dr0_addr_mask = amd_get_dr_addr_mask(0);
4546 		hostsa->dr1_addr_mask = amd_get_dr_addr_mask(1);
4547 		hostsa->dr2_addr_mask = amd_get_dr_addr_mask(2);
4548 		hostsa->dr3_addr_mask = amd_get_dr_addr_mask(3);
4549 	}
4550 }
4551 
4552 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4553 {
4554 	struct vcpu_svm *svm = to_svm(vcpu);
4555 
4556 	/* First SIPI: Use the values as initially set by the VMM */
4557 	if (!svm->sev_es.received_first_sipi) {
4558 		svm->sev_es.received_first_sipi = true;
4559 		return;
4560 	}
4561 
4562 	/* Subsequent SIPI */
4563 	switch (svm->sev_es.ap_reset_hold_type) {
4564 	case AP_RESET_HOLD_NAE_EVENT:
4565 		/*
4566 		 * Return from an AP Reset Hold VMGEXIT, where the guest will
4567 		 * set the CS and RIP. Set SW_EXIT_INFO_2 to a non-zero value.
4568 		 */
4569 		svm_vmgexit_success(svm, 1);
4570 		break;
4571 	case AP_RESET_HOLD_MSR_PROTO:
4572 		/*
4573 		 * Return from an AP Reset Hold VMGEXIT, where the guest will
4574 		 * set the CS and RIP. Set GHCB data field to a non-zero value.
4575 		 */
4576 		set_ghcb_msr_bits(svm, 1,
4577 				  GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,
4578 				  GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
4579 
4580 		set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP,
4581 				  GHCB_MSR_INFO_MASK,
4582 				  GHCB_MSR_INFO_POS);
4583 		break;
4584 	default:
4585 		break;
4586 	}
4587 }
4588 
4589 struct page *snp_safe_alloc_page_node(int node, gfp_t gfp)
4590 {
4591 	unsigned long pfn;
4592 	struct page *p;
4593 
4594 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
4595 		return alloc_pages_node(node, gfp | __GFP_ZERO, 0);
4596 
4597 	/*
4598 	 * Allocate an SNP-safe page to workaround the SNP erratum where
4599 	 * the CPU will incorrectly signal an RMP violation #PF if a
4600 	 * hugepage (2MB or 1GB) collides with the RMP entry of a
4601 	 * 2MB-aligned VMCB, VMSA, or AVIC backing page.
4602 	 *
4603 	 * Allocate one extra page, choose a page which is not
4604 	 * 2MB-aligned, and free the other.
4605 	 */
4606 	p = alloc_pages_node(node, gfp | __GFP_ZERO, 1);
4607 	if (!p)
4608 		return NULL;
4609 
4610 	split_page(p, 1);
4611 
4612 	pfn = page_to_pfn(p);
4613 	if (IS_ALIGNED(pfn, PTRS_PER_PMD))
4614 		__free_page(p++);
4615 	else
4616 		__free_page(p + 1);
4617 
4618 	return p;
4619 }
4620 
4621 void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
4622 {
4623 	struct kvm_memory_slot *slot;
4624 	struct kvm *kvm = vcpu->kvm;
4625 	int order, rmp_level, ret;
4626 	struct page *page;
4627 	bool assigned;
4628 	kvm_pfn_t pfn;
4629 	gfn_t gfn;
4630 
4631 	gfn = gpa >> PAGE_SHIFT;
4632 
4633 	/*
4634 	 * The only time RMP faults occur for shared pages is when the guest is
4635 	 * triggering an RMP fault for an implicit page-state change from
4636 	 * shared->private. Implicit page-state changes are forwarded to
4637 	 * userspace via KVM_EXIT_MEMORY_FAULT events, however, so RMP faults
4638 	 * for shared pages should not end up here.
4639 	 */
4640 	if (!kvm_mem_is_private(kvm, gfn)) {
4641 		pr_warn_ratelimited("SEV: Unexpected RMP fault for non-private GPA 0x%llx\n",
4642 				    gpa);
4643 		return;
4644 	}
4645 
4646 	slot = gfn_to_memslot(kvm, gfn);
4647 	if (!kvm_slot_can_be_private(slot)) {
4648 		pr_warn_ratelimited("SEV: Unexpected RMP fault, non-private slot for GPA 0x%llx\n",
4649 				    gpa);
4650 		return;
4651 	}
4652 
4653 	ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order);
4654 	if (ret) {
4655 		pr_warn_ratelimited("SEV: Unexpected RMP fault, no backing page for private GPA 0x%llx\n",
4656 				    gpa);
4657 		return;
4658 	}
4659 
4660 	ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
4661 	if (ret || !assigned) {
4662 		pr_warn_ratelimited("SEV: Unexpected RMP fault, no assigned RMP entry found for GPA 0x%llx PFN 0x%llx error %d\n",
4663 				    gpa, pfn, ret);
4664 		goto out_no_trace;
4665 	}
4666 
4667 	/*
4668 	 * There are 2 cases where a PSMASH may be needed to resolve an #NPF
4669 	 * with PFERR_GUEST_RMP_BIT set:
4670 	 *
4671 	 * 1) RMPADJUST/PVALIDATE can trigger an #NPF with PFERR_GUEST_SIZEM
4672 	 *    bit set if the guest issues them with a smaller granularity than
4673 	 *    what is indicated by the page-size bit in the 2MB RMP entry for
4674 	 *    the PFN that backs the GPA.
4675 	 *
4676 	 * 2) Guest access via NPT can trigger an #NPF if the NPT mapping is
4677 	 *    smaller than what is indicated by the 2MB RMP entry for the PFN
4678 	 *    that backs the GPA.
4679 	 *
4680 	 * In both these cases, the corresponding 2M RMP entry needs to
4681 	 * be PSMASH'd to 512 4K RMP entries.  If the RMP entry is already
4682 	 * split into 4K RMP entries, then this is likely a spurious case which
4683 	 * can occur when there are concurrent accesses by the guest to a 2MB
4684 	 * GPA range that is backed by a 2MB-aligned PFN who's RMP entry is in
4685 	 * the process of being PMASH'd into 4K entries. These cases should
4686 	 * resolve automatically on subsequent accesses, so just ignore them
4687 	 * here.
4688 	 */
4689 	if (rmp_level == PG_LEVEL_4K)
4690 		goto out;
4691 
4692 	ret = snp_rmptable_psmash(pfn);
4693 	if (ret) {
4694 		/*
4695 		 * Look it up again. If it's 4K now then the PSMASH may have
4696 		 * raced with another process and the issue has already resolved
4697 		 * itself.
4698 		 */
4699 		if (!snp_lookup_rmpentry(pfn, &assigned, &rmp_level) &&
4700 		    assigned && rmp_level == PG_LEVEL_4K)
4701 			goto out;
4702 
4703 		pr_warn_ratelimited("SEV: Unable to split RMP entry for GPA 0x%llx PFN 0x%llx ret %d\n",
4704 				    gpa, pfn, ret);
4705 	}
4706 
4707 	kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD);
4708 out:
4709 	trace_kvm_rmp_fault(vcpu, gpa, pfn, error_code, rmp_level, ret);
4710 out_no_trace:
4711 	kvm_release_page_unused(page);
4712 }
4713 
4714 static bool is_pfn_range_shared(kvm_pfn_t start, kvm_pfn_t end)
4715 {
4716 	kvm_pfn_t pfn = start;
4717 
4718 	while (pfn < end) {
4719 		int ret, rmp_level;
4720 		bool assigned;
4721 
4722 		ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
4723 		if (ret) {
4724 			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",
4725 					    pfn, start, end, rmp_level, ret);
4726 			return false;
4727 		}
4728 
4729 		if (assigned) {
4730 			pr_debug("%s: overlap detected, PFN 0x%llx start 0x%llx end 0x%llx RMP level %d\n",
4731 				 __func__, pfn, start, end, rmp_level);
4732 			return false;
4733 		}
4734 
4735 		pfn++;
4736 	}
4737 
4738 	return true;
4739 }
4740 
4741 static u8 max_level_for_order(int order)
4742 {
4743 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
4744 		return PG_LEVEL_2M;
4745 
4746 	return PG_LEVEL_4K;
4747 }
4748 
4749 static bool is_large_rmp_possible(struct kvm *kvm, kvm_pfn_t pfn, int order)
4750 {
4751 	kvm_pfn_t pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD);
4752 
4753 	/*
4754 	 * If this is a large folio, and the entire 2M range containing the
4755 	 * PFN is currently shared, then the entire 2M-aligned range can be
4756 	 * set to private via a single 2M RMP entry.
4757 	 */
4758 	if (max_level_for_order(order) > PG_LEVEL_4K &&
4759 	    is_pfn_range_shared(pfn_aligned, pfn_aligned + PTRS_PER_PMD))
4760 		return true;
4761 
4762 	return false;
4763 }
4764 
4765 int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, int max_order)
4766 {
4767 	struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
4768 	kvm_pfn_t pfn_aligned;
4769 	gfn_t gfn_aligned;
4770 	int level, rc;
4771 	bool assigned;
4772 
4773 	if (!sev_snp_guest(kvm))
4774 		return 0;
4775 
4776 	rc = snp_lookup_rmpentry(pfn, &assigned, &level);
4777 	if (rc) {
4778 		pr_err_ratelimited("SEV: Failed to look up RMP entry: GFN %llx PFN %llx error %d\n",
4779 				   gfn, pfn, rc);
4780 		return -ENOENT;
4781 	}
4782 
4783 	if (assigned) {
4784 		pr_debug("%s: already assigned: gfn %llx pfn %llx max_order %d level %d\n",
4785 			 __func__, gfn, pfn, max_order, level);
4786 		return 0;
4787 	}
4788 
4789 	if (is_large_rmp_possible(kvm, pfn, max_order)) {
4790 		level = PG_LEVEL_2M;
4791 		pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD);
4792 		gfn_aligned = ALIGN_DOWN(gfn, PTRS_PER_PMD);
4793 	} else {
4794 		level = PG_LEVEL_4K;
4795 		pfn_aligned = pfn;
4796 		gfn_aligned = gfn;
4797 	}
4798 
4799 	rc = rmp_make_private(pfn_aligned, gfn_to_gpa(gfn_aligned), level, sev->asid, false);
4800 	if (rc) {
4801 		pr_err_ratelimited("SEV: Failed to update RMP entry: GFN %llx PFN %llx level %d error %d\n",
4802 				   gfn, pfn, level, rc);
4803 		return -EINVAL;
4804 	}
4805 
4806 	pr_debug("%s: updated: gfn %llx pfn %llx pfn_aligned %llx max_order %d level %d\n",
4807 		 __func__, gfn, pfn, pfn_aligned, max_order, level);
4808 
4809 	return 0;
4810 }
4811 
4812 void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
4813 {
4814 	kvm_pfn_t pfn;
4815 
4816 	if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
4817 		return;
4818 
4819 	pr_debug("%s: PFN start 0x%llx PFN end 0x%llx\n", __func__, start, end);
4820 
4821 	for (pfn = start; pfn < end;) {
4822 		bool use_2m_update = false;
4823 		int rc, rmp_level;
4824 		bool assigned;
4825 
4826 		rc = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
4827 		if (rc || !assigned)
4828 			goto next_pfn;
4829 
4830 		use_2m_update = IS_ALIGNED(pfn, PTRS_PER_PMD) &&
4831 				end >= (pfn + PTRS_PER_PMD) &&
4832 				rmp_level > PG_LEVEL_4K;
4833 
4834 		/*
4835 		 * If an unaligned PFN corresponds to a 2M region assigned as a
4836 		 * large page in the RMP table, PSMASH the region into individual
4837 		 * 4K RMP entries before attempting to convert a 4K sub-page.
4838 		 */
4839 		if (!use_2m_update && rmp_level > PG_LEVEL_4K) {
4840 			/*
4841 			 * This shouldn't fail, but if it does, report it, but
4842 			 * still try to update RMP entry to shared and pray this
4843 			 * was a spurious error that can be addressed later.
4844 			 */
4845 			rc = snp_rmptable_psmash(pfn);
4846 			WARN_ONCE(rc, "SEV: Failed to PSMASH RMP entry for PFN 0x%llx error %d\n",
4847 				  pfn, rc);
4848 		}
4849 
4850 		rc = rmp_make_shared(pfn, use_2m_update ? PG_LEVEL_2M : PG_LEVEL_4K);
4851 		if (WARN_ONCE(rc, "SEV: Failed to update RMP entry for PFN 0x%llx error %d\n",
4852 			      pfn, rc))
4853 			goto next_pfn;
4854 
4855 		/*
4856 		 * SEV-ES avoids host/guest cache coherency issues through
4857 		 * WBINVD hooks issued via MMU notifiers during run-time, and
4858 		 * KVM's VM destroy path at shutdown. Those MMU notifier events
4859 		 * don't cover gmem since there is no requirement to map pages
4860 		 * to a HVA in order to use them for a running guest. While the
4861 		 * shutdown path would still likely cover things for SNP guests,
4862 		 * userspace may also free gmem pages during run-time via
4863 		 * hole-punching operations on the guest_memfd, so flush the
4864 		 * cache entries for these pages before free'ing them back to
4865 		 * the host.
4866 		 */
4867 		clflush_cache_range(__va(pfn_to_hpa(pfn)),
4868 				    use_2m_update ? PMD_SIZE : PAGE_SIZE);
4869 next_pfn:
4870 		pfn += use_2m_update ? PTRS_PER_PMD : 1;
4871 		cond_resched();
4872 	}
4873 }
4874 
4875 int sev_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn)
4876 {
4877 	int level, rc;
4878 	bool assigned;
4879 
4880 	if (!sev_snp_guest(kvm))
4881 		return 0;
4882 
4883 	rc = snp_lookup_rmpentry(pfn, &assigned, &level);
4884 	if (rc || !assigned)
4885 		return PG_LEVEL_4K;
4886 
4887 	return level;
4888 }
4889 
4890 struct vmcb_save_area *sev_decrypt_vmsa(struct kvm_vcpu *vcpu)
4891 {
4892 	struct vcpu_svm *svm = to_svm(vcpu);
4893 	struct vmcb_save_area *vmsa;
4894 	struct kvm_sev_info *sev;
4895 	int error = 0;
4896 	int ret;
4897 
4898 	if (!sev_es_guest(vcpu->kvm))
4899 		return NULL;
4900 
4901 	/*
4902 	 * If the VMSA has not yet been encrypted, return a pointer to the
4903 	 * current un-encrypted VMSA.
4904 	 */
4905 	if (!vcpu->arch.guest_state_protected)
4906 		return (struct vmcb_save_area *)svm->sev_es.vmsa;
4907 
4908 	sev = to_kvm_sev_info(vcpu->kvm);
4909 
4910 	/* Check if the SEV policy allows debugging */
4911 	if (sev_snp_guest(vcpu->kvm)) {
4912 		if (!(sev->policy & SNP_POLICY_DEBUG))
4913 			return NULL;
4914 	} else {
4915 		if (sev->policy & SEV_POLICY_NODBG)
4916 			return NULL;
4917 	}
4918 
4919 	if (sev_snp_guest(vcpu->kvm)) {
4920 		struct sev_data_snp_dbg dbg = {0};
4921 
4922 		vmsa = snp_alloc_firmware_page(__GFP_ZERO);
4923 		if (!vmsa)
4924 			return NULL;
4925 
4926 		dbg.gctx_paddr = __psp_pa(sev->snp_context);
4927 		dbg.src_addr = svm->vmcb->control.vmsa_pa;
4928 		dbg.dst_addr = __psp_pa(vmsa);
4929 
4930 		ret = sev_do_cmd(SEV_CMD_SNP_DBG_DECRYPT, &dbg, &error);
4931 
4932 		/*
4933 		 * Return the target page to a hypervisor page no matter what.
4934 		 * If this fails, the page can't be used, so leak it and don't
4935 		 * try to use it.
4936 		 */
4937 		if (snp_page_reclaim(vcpu->kvm, PHYS_PFN(__pa(vmsa))))
4938 			return NULL;
4939 
4940 		if (ret) {
4941 			pr_err("SEV: SNP_DBG_DECRYPT failed ret=%d, fw_error=%d (%#x)\n",
4942 			       ret, error, error);
4943 			free_page((unsigned long)vmsa);
4944 
4945 			return NULL;
4946 		}
4947 	} else {
4948 		struct sev_data_dbg dbg = {0};
4949 		struct page *vmsa_page;
4950 
4951 		vmsa_page = alloc_page(GFP_KERNEL);
4952 		if (!vmsa_page)
4953 			return NULL;
4954 
4955 		vmsa = page_address(vmsa_page);
4956 
4957 		dbg.handle = sev->handle;
4958 		dbg.src_addr = svm->vmcb->control.vmsa_pa;
4959 		dbg.dst_addr = __psp_pa(vmsa);
4960 		dbg.len = PAGE_SIZE;
4961 
4962 		ret = sev_do_cmd(SEV_CMD_DBG_DECRYPT, &dbg, &error);
4963 		if (ret) {
4964 			pr_err("SEV: SEV_CMD_DBG_DECRYPT failed ret=%d, fw_error=%d (0x%x)\n",
4965 			       ret, error, error);
4966 			__free_page(vmsa_page);
4967 
4968 			return NULL;
4969 		}
4970 	}
4971 
4972 	return vmsa;
4973 }
4974 
4975 void sev_free_decrypted_vmsa(struct kvm_vcpu *vcpu, struct vmcb_save_area *vmsa)
4976 {
4977 	/* If the VMSA has not yet been encrypted, nothing was allocated */
4978 	if (!vcpu->arch.guest_state_protected || !vmsa)
4979 		return;
4980 
4981 	free_page((unsigned long)vmsa);
4982 }
4983