xref: /openbmc/linux/arch/x86/kvm/svm/sev.c (revision 25b892b5)
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 
10 #include <linux/kvm_types.h>
11 #include <linux/kvm_host.h>
12 #include <linux/kernel.h>
13 #include <linux/highmem.h>
14 #include <linux/psp-sev.h>
15 #include <linux/pagemap.h>
16 #include <linux/swap.h>
17 #include <linux/misc_cgroup.h>
18 #include <linux/processor.h>
19 #include <linux/trace_events.h>
20 #include <asm/fpu/internal.h>
21 
22 #include <asm/pkru.h>
23 #include <asm/trapnr.h>
24 
25 #include "x86.h"
26 #include "svm.h"
27 #include "svm_ops.h"
28 #include "cpuid.h"
29 #include "trace.h"
30 
31 #ifndef CONFIG_KVM_AMD_SEV
32 /*
33  * When this config is not defined, SEV feature is not supported and APIs in
34  * this file are not used but this file still gets compiled into the KVM AMD
35  * module.
36  *
37  * We will not have MISC_CG_RES_SEV and MISC_CG_RES_SEV_ES entries in the enum
38  * misc_res_type {} defined in linux/misc_cgroup.h.
39  *
40  * Below macros allow compilation to succeed.
41  */
42 #define MISC_CG_RES_SEV MISC_CG_RES_TYPES
43 #define MISC_CG_RES_SEV_ES MISC_CG_RES_TYPES
44 #endif
45 
46 #ifdef CONFIG_KVM_AMD_SEV
47 /* enable/disable SEV support */
48 static bool sev_enabled = true;
49 module_param_named(sev, sev_enabled, bool, 0444);
50 
51 /* enable/disable SEV-ES support */
52 static bool sev_es_enabled = true;
53 module_param_named(sev_es, sev_es_enabled, bool, 0444);
54 #else
55 #define sev_enabled false
56 #define sev_es_enabled false
57 #endif /* CONFIG_KVM_AMD_SEV */
58 
59 static u8 sev_enc_bit;
60 static DECLARE_RWSEM(sev_deactivate_lock);
61 static DEFINE_MUTEX(sev_bitmap_lock);
62 unsigned int max_sev_asid;
63 static unsigned int min_sev_asid;
64 static unsigned long sev_me_mask;
65 static unsigned int nr_asids;
66 static unsigned long *sev_asid_bitmap;
67 static unsigned long *sev_reclaim_asid_bitmap;
68 
69 struct enc_region {
70 	struct list_head list;
71 	unsigned long npages;
72 	struct page **pages;
73 	unsigned long uaddr;
74 	unsigned long size;
75 };
76 
77 /* Called with the sev_bitmap_lock held, or on shutdown  */
78 static int sev_flush_asids(int min_asid, int max_asid)
79 {
80 	int ret, asid, error = 0;
81 
82 	/* Check if there are any ASIDs to reclaim before performing a flush */
83 	asid = find_next_bit(sev_reclaim_asid_bitmap, nr_asids, min_asid);
84 	if (asid > max_asid)
85 		return -EBUSY;
86 
87 	/*
88 	 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
89 	 * so it must be guarded.
90 	 */
91 	down_write(&sev_deactivate_lock);
92 
93 	wbinvd_on_all_cpus();
94 	ret = sev_guest_df_flush(&error);
95 
96 	up_write(&sev_deactivate_lock);
97 
98 	if (ret)
99 		pr_err("SEV: DF_FLUSH failed, ret=%d, error=%#x\n", ret, error);
100 
101 	return ret;
102 }
103 
104 static inline bool is_mirroring_enc_context(struct kvm *kvm)
105 {
106 	return !!to_kvm_svm(kvm)->sev_info.enc_context_owner;
107 }
108 
109 /* Must be called with the sev_bitmap_lock held */
110 static bool __sev_recycle_asids(int min_asid, int max_asid)
111 {
112 	if (sev_flush_asids(min_asid, max_asid))
113 		return false;
114 
115 	/* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */
116 	bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
117 		   nr_asids);
118 	bitmap_zero(sev_reclaim_asid_bitmap, nr_asids);
119 
120 	return true;
121 }
122 
123 static int sev_asid_new(struct kvm_sev_info *sev)
124 {
125 	int asid, min_asid, max_asid, ret;
126 	bool retry = true;
127 	enum misc_res_type type;
128 
129 	type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
130 	WARN_ON(sev->misc_cg);
131 	sev->misc_cg = get_current_misc_cg();
132 	ret = misc_cg_try_charge(type, sev->misc_cg, 1);
133 	if (ret) {
134 		put_misc_cg(sev->misc_cg);
135 		sev->misc_cg = NULL;
136 		return ret;
137 	}
138 
139 	mutex_lock(&sev_bitmap_lock);
140 
141 	/*
142 	 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid.
143 	 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1.
144 	 */
145 	min_asid = sev->es_active ? 1 : min_sev_asid;
146 	max_asid = sev->es_active ? min_sev_asid - 1 : max_sev_asid;
147 again:
148 	asid = find_next_zero_bit(sev_asid_bitmap, max_asid + 1, min_asid);
149 	if (asid > max_asid) {
150 		if (retry && __sev_recycle_asids(min_asid, max_asid)) {
151 			retry = false;
152 			goto again;
153 		}
154 		mutex_unlock(&sev_bitmap_lock);
155 		ret = -EBUSY;
156 		goto e_uncharge;
157 	}
158 
159 	__set_bit(asid, sev_asid_bitmap);
160 
161 	mutex_unlock(&sev_bitmap_lock);
162 
163 	return asid;
164 e_uncharge:
165 	misc_cg_uncharge(type, sev->misc_cg, 1);
166 	put_misc_cg(sev->misc_cg);
167 	sev->misc_cg = NULL;
168 	return ret;
169 }
170 
171 static int sev_get_asid(struct kvm *kvm)
172 {
173 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
174 
175 	return sev->asid;
176 }
177 
178 static void sev_asid_free(struct kvm_sev_info *sev)
179 {
180 	struct svm_cpu_data *sd;
181 	int cpu;
182 	enum misc_res_type type;
183 
184 	mutex_lock(&sev_bitmap_lock);
185 
186 	__set_bit(sev->asid, sev_reclaim_asid_bitmap);
187 
188 	for_each_possible_cpu(cpu) {
189 		sd = per_cpu(svm_data, cpu);
190 		sd->sev_vmcbs[sev->asid] = NULL;
191 	}
192 
193 	mutex_unlock(&sev_bitmap_lock);
194 
195 	type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
196 	misc_cg_uncharge(type, sev->misc_cg, 1);
197 	put_misc_cg(sev->misc_cg);
198 	sev->misc_cg = NULL;
199 }
200 
201 static void sev_decommission(unsigned int handle)
202 {
203 	struct sev_data_decommission decommission;
204 
205 	if (!handle)
206 		return;
207 
208 	decommission.handle = handle;
209 	sev_guest_decommission(&decommission, NULL);
210 }
211 
212 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
213 {
214 	struct sev_data_deactivate deactivate;
215 
216 	if (!handle)
217 		return;
218 
219 	deactivate.handle = handle;
220 
221 	/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
222 	down_read(&sev_deactivate_lock);
223 	sev_guest_deactivate(&deactivate, NULL);
224 	up_read(&sev_deactivate_lock);
225 
226 	sev_decommission(handle);
227 }
228 
229 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
230 {
231 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
232 	bool es_active = argp->id == KVM_SEV_ES_INIT;
233 	int asid, ret;
234 
235 	if (kvm->created_vcpus)
236 		return -EINVAL;
237 
238 	ret = -EBUSY;
239 	if (unlikely(sev->active))
240 		return ret;
241 
242 	sev->es_active = es_active;
243 	asid = sev_asid_new(sev);
244 	if (asid < 0)
245 		goto e_no_asid;
246 	sev->asid = asid;
247 
248 	ret = sev_platform_init(&argp->error);
249 	if (ret)
250 		goto e_free;
251 
252 	sev->active = true;
253 	sev->asid = asid;
254 	INIT_LIST_HEAD(&sev->regions_list);
255 
256 	return 0;
257 
258 e_free:
259 	sev_asid_free(sev);
260 	sev->asid = 0;
261 e_no_asid:
262 	sev->es_active = false;
263 	return ret;
264 }
265 
266 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
267 {
268 	struct sev_data_activate activate;
269 	int asid = sev_get_asid(kvm);
270 	int ret;
271 
272 	/* activate ASID on the given handle */
273 	activate.handle = handle;
274 	activate.asid   = asid;
275 	ret = sev_guest_activate(&activate, error);
276 
277 	return ret;
278 }
279 
280 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
281 {
282 	struct fd f;
283 	int ret;
284 
285 	f = fdget(fd);
286 	if (!f.file)
287 		return -EBADF;
288 
289 	ret = sev_issue_cmd_external_user(f.file, id, data, error);
290 
291 	fdput(f);
292 	return ret;
293 }
294 
295 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
296 {
297 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
298 
299 	return __sev_issue_cmd(sev->fd, id, data, error);
300 }
301 
302 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
303 {
304 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
305 	struct sev_data_launch_start start;
306 	struct kvm_sev_launch_start params;
307 	void *dh_blob, *session_blob;
308 	int *error = &argp->error;
309 	int ret;
310 
311 	if (!sev_guest(kvm))
312 		return -ENOTTY;
313 
314 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
315 		return -EFAULT;
316 
317 	memset(&start, 0, sizeof(start));
318 
319 	dh_blob = NULL;
320 	if (params.dh_uaddr) {
321 		dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
322 		if (IS_ERR(dh_blob))
323 			return PTR_ERR(dh_blob);
324 
325 		start.dh_cert_address = __sme_set(__pa(dh_blob));
326 		start.dh_cert_len = params.dh_len;
327 	}
328 
329 	session_blob = NULL;
330 	if (params.session_uaddr) {
331 		session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
332 		if (IS_ERR(session_blob)) {
333 			ret = PTR_ERR(session_blob);
334 			goto e_free_dh;
335 		}
336 
337 		start.session_address = __sme_set(__pa(session_blob));
338 		start.session_len = params.session_len;
339 	}
340 
341 	start.handle = params.handle;
342 	start.policy = params.policy;
343 
344 	/* create memory encryption context */
345 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, &start, error);
346 	if (ret)
347 		goto e_free_session;
348 
349 	/* Bind ASID to this guest */
350 	ret = sev_bind_asid(kvm, start.handle, error);
351 	if (ret) {
352 		sev_decommission(start.handle);
353 		goto e_free_session;
354 	}
355 
356 	/* return handle to userspace */
357 	params.handle = start.handle;
358 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params))) {
359 		sev_unbind_asid(kvm, start.handle);
360 		ret = -EFAULT;
361 		goto e_free_session;
362 	}
363 
364 	sev->handle = start.handle;
365 	sev->fd = argp->sev_fd;
366 
367 e_free_session:
368 	kfree(session_blob);
369 e_free_dh:
370 	kfree(dh_blob);
371 	return ret;
372 }
373 
374 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
375 				    unsigned long ulen, unsigned long *n,
376 				    int write)
377 {
378 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
379 	unsigned long npages, size;
380 	int npinned;
381 	unsigned long locked, lock_limit;
382 	struct page **pages;
383 	unsigned long first, last;
384 	int ret;
385 
386 	lockdep_assert_held(&kvm->lock);
387 
388 	if (ulen == 0 || uaddr + ulen < uaddr)
389 		return ERR_PTR(-EINVAL);
390 
391 	/* Calculate number of pages. */
392 	first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
393 	last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
394 	npages = (last - first + 1);
395 
396 	locked = sev->pages_locked + npages;
397 	lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
398 	if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
399 		pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
400 		return ERR_PTR(-ENOMEM);
401 	}
402 
403 	if (WARN_ON_ONCE(npages > INT_MAX))
404 		return ERR_PTR(-EINVAL);
405 
406 	/* Avoid using vmalloc for smaller buffers. */
407 	size = npages * sizeof(struct page *);
408 	if (size > PAGE_SIZE)
409 		pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
410 	else
411 		pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
412 
413 	if (!pages)
414 		return ERR_PTR(-ENOMEM);
415 
416 	/* Pin the user virtual address. */
417 	npinned = pin_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
418 	if (npinned != npages) {
419 		pr_err("SEV: Failure locking %lu pages.\n", npages);
420 		ret = -ENOMEM;
421 		goto err;
422 	}
423 
424 	*n = npages;
425 	sev->pages_locked = locked;
426 
427 	return pages;
428 
429 err:
430 	if (npinned > 0)
431 		unpin_user_pages(pages, npinned);
432 
433 	kvfree(pages);
434 	return ERR_PTR(ret);
435 }
436 
437 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
438 			     unsigned long npages)
439 {
440 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
441 
442 	unpin_user_pages(pages, npages);
443 	kvfree(pages);
444 	sev->pages_locked -= npages;
445 }
446 
447 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
448 {
449 	uint8_t *page_virtual;
450 	unsigned long i;
451 
452 	if (this_cpu_has(X86_FEATURE_SME_COHERENT) || npages == 0 ||
453 	    pages == NULL)
454 		return;
455 
456 	for (i = 0; i < npages; i++) {
457 		page_virtual = kmap_atomic(pages[i]);
458 		clflush_cache_range(page_virtual, PAGE_SIZE);
459 		kunmap_atomic(page_virtual);
460 	}
461 }
462 
463 static unsigned long get_num_contig_pages(unsigned long idx,
464 				struct page **inpages, unsigned long npages)
465 {
466 	unsigned long paddr, next_paddr;
467 	unsigned long i = idx + 1, pages = 1;
468 
469 	/* find the number of contiguous pages starting from idx */
470 	paddr = __sme_page_pa(inpages[idx]);
471 	while (i < npages) {
472 		next_paddr = __sme_page_pa(inpages[i++]);
473 		if ((paddr + PAGE_SIZE) == next_paddr) {
474 			pages++;
475 			paddr = next_paddr;
476 			continue;
477 		}
478 		break;
479 	}
480 
481 	return pages;
482 }
483 
484 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
485 {
486 	unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
487 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
488 	struct kvm_sev_launch_update_data params;
489 	struct sev_data_launch_update_data data;
490 	struct page **inpages;
491 	int ret;
492 
493 	if (!sev_guest(kvm))
494 		return -ENOTTY;
495 
496 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
497 		return -EFAULT;
498 
499 	vaddr = params.uaddr;
500 	size = params.len;
501 	vaddr_end = vaddr + size;
502 
503 	/* Lock the user memory. */
504 	inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
505 	if (IS_ERR(inpages))
506 		return PTR_ERR(inpages);
507 
508 	/*
509 	 * Flush (on non-coherent CPUs) before LAUNCH_UPDATE encrypts pages in
510 	 * place; the cache may contain the data that was written unencrypted.
511 	 */
512 	sev_clflush_pages(inpages, npages);
513 
514 	data.reserved = 0;
515 	data.handle = sev->handle;
516 
517 	for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
518 		int offset, len;
519 
520 		/*
521 		 * If the user buffer is not page-aligned, calculate the offset
522 		 * within the page.
523 		 */
524 		offset = vaddr & (PAGE_SIZE - 1);
525 
526 		/* Calculate the number of pages that can be encrypted in one go. */
527 		pages = get_num_contig_pages(i, inpages, npages);
528 
529 		len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
530 
531 		data.len = len;
532 		data.address = __sme_page_pa(inpages[i]) + offset;
533 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, &data, &argp->error);
534 		if (ret)
535 			goto e_unpin;
536 
537 		size -= len;
538 		next_vaddr = vaddr + len;
539 	}
540 
541 e_unpin:
542 	/* content of memory is updated, mark pages dirty */
543 	for (i = 0; i < npages; i++) {
544 		set_page_dirty_lock(inpages[i]);
545 		mark_page_accessed(inpages[i]);
546 	}
547 	/* unlock the user pages */
548 	sev_unpin_memory(kvm, inpages, npages);
549 	return ret;
550 }
551 
552 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
553 {
554 	struct vmcb_save_area *save = &svm->vmcb->save;
555 
556 	/* Check some debug related fields before encrypting the VMSA */
557 	if (svm->vcpu.guest_debug || (save->dr7 & ~DR7_FIXED_1))
558 		return -EINVAL;
559 
560 	/* Sync registgers */
561 	save->rax = svm->vcpu.arch.regs[VCPU_REGS_RAX];
562 	save->rbx = svm->vcpu.arch.regs[VCPU_REGS_RBX];
563 	save->rcx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
564 	save->rdx = svm->vcpu.arch.regs[VCPU_REGS_RDX];
565 	save->rsp = svm->vcpu.arch.regs[VCPU_REGS_RSP];
566 	save->rbp = svm->vcpu.arch.regs[VCPU_REGS_RBP];
567 	save->rsi = svm->vcpu.arch.regs[VCPU_REGS_RSI];
568 	save->rdi = svm->vcpu.arch.regs[VCPU_REGS_RDI];
569 #ifdef CONFIG_X86_64
570 	save->r8  = svm->vcpu.arch.regs[VCPU_REGS_R8];
571 	save->r9  = svm->vcpu.arch.regs[VCPU_REGS_R9];
572 	save->r10 = svm->vcpu.arch.regs[VCPU_REGS_R10];
573 	save->r11 = svm->vcpu.arch.regs[VCPU_REGS_R11];
574 	save->r12 = svm->vcpu.arch.regs[VCPU_REGS_R12];
575 	save->r13 = svm->vcpu.arch.regs[VCPU_REGS_R13];
576 	save->r14 = svm->vcpu.arch.regs[VCPU_REGS_R14];
577 	save->r15 = svm->vcpu.arch.regs[VCPU_REGS_R15];
578 #endif
579 	save->rip = svm->vcpu.arch.regs[VCPU_REGS_RIP];
580 
581 	/* Sync some non-GPR registers before encrypting */
582 	save->xcr0 = svm->vcpu.arch.xcr0;
583 	save->pkru = svm->vcpu.arch.pkru;
584 	save->xss  = svm->vcpu.arch.ia32_xss;
585 	save->dr6  = svm->vcpu.arch.dr6;
586 
587 	/*
588 	 * SEV-ES will use a VMSA that is pointed to by the VMCB, not
589 	 * the traditional VMSA that is part of the VMCB. Copy the
590 	 * traditional VMSA as it has been built so far (in prep
591 	 * for LAUNCH_UPDATE_VMSA) to be the initial SEV-ES state.
592 	 */
593 	memcpy(svm->vmsa, save, sizeof(*save));
594 
595 	return 0;
596 }
597 
598 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
599 {
600 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
601 	struct sev_data_launch_update_vmsa vmsa;
602 	struct kvm_vcpu *vcpu;
603 	int i, ret;
604 
605 	if (!sev_es_guest(kvm))
606 		return -ENOTTY;
607 
608 	vmsa.reserved = 0;
609 
610 	kvm_for_each_vcpu(i, vcpu, kvm) {
611 		struct vcpu_svm *svm = to_svm(vcpu);
612 
613 		/* Perform some pre-encryption checks against the VMSA */
614 		ret = sev_es_sync_vmsa(svm);
615 		if (ret)
616 			return ret;
617 
618 		/*
619 		 * The LAUNCH_UPDATE_VMSA command will perform in-place
620 		 * encryption of the VMSA memory content (i.e it will write
621 		 * the same memory region with the guest's key), so invalidate
622 		 * it first.
623 		 */
624 		clflush_cache_range(svm->vmsa, PAGE_SIZE);
625 
626 		vmsa.handle = sev->handle;
627 		vmsa.address = __sme_pa(svm->vmsa);
628 		vmsa.len = PAGE_SIZE;
629 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_VMSA, &vmsa,
630 				    &argp->error);
631 		if (ret)
632 			return ret;
633 
634 		svm->vcpu.arch.guest_state_protected = true;
635 	}
636 
637 	return 0;
638 }
639 
640 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
641 {
642 	void __user *measure = (void __user *)(uintptr_t)argp->data;
643 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
644 	struct sev_data_launch_measure data;
645 	struct kvm_sev_launch_measure params;
646 	void __user *p = NULL;
647 	void *blob = NULL;
648 	int ret;
649 
650 	if (!sev_guest(kvm))
651 		return -ENOTTY;
652 
653 	if (copy_from_user(&params, measure, sizeof(params)))
654 		return -EFAULT;
655 
656 	memset(&data, 0, sizeof(data));
657 
658 	/* User wants to query the blob length */
659 	if (!params.len)
660 		goto cmd;
661 
662 	p = (void __user *)(uintptr_t)params.uaddr;
663 	if (p) {
664 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
665 			return -EINVAL;
666 
667 		blob = kmalloc(params.len, GFP_KERNEL_ACCOUNT);
668 		if (!blob)
669 			return -ENOMEM;
670 
671 		data.address = __psp_pa(blob);
672 		data.len = params.len;
673 	}
674 
675 cmd:
676 	data.handle = sev->handle;
677 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, &data, &argp->error);
678 
679 	/*
680 	 * If we query the session length, FW responded with expected data.
681 	 */
682 	if (!params.len)
683 		goto done;
684 
685 	if (ret)
686 		goto e_free_blob;
687 
688 	if (blob) {
689 		if (copy_to_user(p, blob, params.len))
690 			ret = -EFAULT;
691 	}
692 
693 done:
694 	params.len = data.len;
695 	if (copy_to_user(measure, &params, sizeof(params)))
696 		ret = -EFAULT;
697 e_free_blob:
698 	kfree(blob);
699 	return ret;
700 }
701 
702 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
703 {
704 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
705 	struct sev_data_launch_finish data;
706 
707 	if (!sev_guest(kvm))
708 		return -ENOTTY;
709 
710 	data.handle = sev->handle;
711 	return sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, &data, &argp->error);
712 }
713 
714 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
715 {
716 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
717 	struct kvm_sev_guest_status params;
718 	struct sev_data_guest_status data;
719 	int ret;
720 
721 	if (!sev_guest(kvm))
722 		return -ENOTTY;
723 
724 	memset(&data, 0, sizeof(data));
725 
726 	data.handle = sev->handle;
727 	ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, &data, &argp->error);
728 	if (ret)
729 		return ret;
730 
731 	params.policy = data.policy;
732 	params.state = data.state;
733 	params.handle = data.handle;
734 
735 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
736 		ret = -EFAULT;
737 
738 	return ret;
739 }
740 
741 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
742 			       unsigned long dst, int size,
743 			       int *error, bool enc)
744 {
745 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
746 	struct sev_data_dbg data;
747 
748 	data.reserved = 0;
749 	data.handle = sev->handle;
750 	data.dst_addr = dst;
751 	data.src_addr = src;
752 	data.len = size;
753 
754 	return sev_issue_cmd(kvm,
755 			     enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
756 			     &data, error);
757 }
758 
759 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
760 			     unsigned long dst_paddr, int sz, int *err)
761 {
762 	int offset;
763 
764 	/*
765 	 * Its safe to read more than we are asked, caller should ensure that
766 	 * destination has enough space.
767 	 */
768 	offset = src_paddr & 15;
769 	src_paddr = round_down(src_paddr, 16);
770 	sz = round_up(sz + offset, 16);
771 
772 	return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
773 }
774 
775 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
776 				  void __user *dst_uaddr,
777 				  unsigned long dst_paddr,
778 				  int size, int *err)
779 {
780 	struct page *tpage = NULL;
781 	int ret, offset;
782 
783 	/* if inputs are not 16-byte then use intermediate buffer */
784 	if (!IS_ALIGNED(dst_paddr, 16) ||
785 	    !IS_ALIGNED(paddr,     16) ||
786 	    !IS_ALIGNED(size,      16)) {
787 		tpage = (void *)alloc_page(GFP_KERNEL);
788 		if (!tpage)
789 			return -ENOMEM;
790 
791 		dst_paddr = __sme_page_pa(tpage);
792 	}
793 
794 	ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
795 	if (ret)
796 		goto e_free;
797 
798 	if (tpage) {
799 		offset = paddr & 15;
800 		if (copy_to_user(dst_uaddr, page_address(tpage) + offset, size))
801 			ret = -EFAULT;
802 	}
803 
804 e_free:
805 	if (tpage)
806 		__free_page(tpage);
807 
808 	return ret;
809 }
810 
811 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
812 				  void __user *vaddr,
813 				  unsigned long dst_paddr,
814 				  void __user *dst_vaddr,
815 				  int size, int *error)
816 {
817 	struct page *src_tpage = NULL;
818 	struct page *dst_tpage = NULL;
819 	int ret, len = size;
820 
821 	/* If source buffer is not aligned then use an intermediate buffer */
822 	if (!IS_ALIGNED((unsigned long)vaddr, 16)) {
823 		src_tpage = alloc_page(GFP_KERNEL);
824 		if (!src_tpage)
825 			return -ENOMEM;
826 
827 		if (copy_from_user(page_address(src_tpage), vaddr, size)) {
828 			__free_page(src_tpage);
829 			return -EFAULT;
830 		}
831 
832 		paddr = __sme_page_pa(src_tpage);
833 	}
834 
835 	/*
836 	 *  If destination buffer or length is not aligned then do read-modify-write:
837 	 *   - decrypt destination in an intermediate buffer
838 	 *   - copy the source buffer in an intermediate buffer
839 	 *   - use the intermediate buffer as source buffer
840 	 */
841 	if (!IS_ALIGNED((unsigned long)dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
842 		int dst_offset;
843 
844 		dst_tpage = alloc_page(GFP_KERNEL);
845 		if (!dst_tpage) {
846 			ret = -ENOMEM;
847 			goto e_free;
848 		}
849 
850 		ret = __sev_dbg_decrypt(kvm, dst_paddr,
851 					__sme_page_pa(dst_tpage), size, error);
852 		if (ret)
853 			goto e_free;
854 
855 		/*
856 		 *  If source is kernel buffer then use memcpy() otherwise
857 		 *  copy_from_user().
858 		 */
859 		dst_offset = dst_paddr & 15;
860 
861 		if (src_tpage)
862 			memcpy(page_address(dst_tpage) + dst_offset,
863 			       page_address(src_tpage), size);
864 		else {
865 			if (copy_from_user(page_address(dst_tpage) + dst_offset,
866 					   vaddr, size)) {
867 				ret = -EFAULT;
868 				goto e_free;
869 			}
870 		}
871 
872 		paddr = __sme_page_pa(dst_tpage);
873 		dst_paddr = round_down(dst_paddr, 16);
874 		len = round_up(size, 16);
875 	}
876 
877 	ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
878 
879 e_free:
880 	if (src_tpage)
881 		__free_page(src_tpage);
882 	if (dst_tpage)
883 		__free_page(dst_tpage);
884 	return ret;
885 }
886 
887 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
888 {
889 	unsigned long vaddr, vaddr_end, next_vaddr;
890 	unsigned long dst_vaddr;
891 	struct page **src_p, **dst_p;
892 	struct kvm_sev_dbg debug;
893 	unsigned long n;
894 	unsigned int size;
895 	int ret;
896 
897 	if (!sev_guest(kvm))
898 		return -ENOTTY;
899 
900 	if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
901 		return -EFAULT;
902 
903 	if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
904 		return -EINVAL;
905 	if (!debug.dst_uaddr)
906 		return -EINVAL;
907 
908 	vaddr = debug.src_uaddr;
909 	size = debug.len;
910 	vaddr_end = vaddr + size;
911 	dst_vaddr = debug.dst_uaddr;
912 
913 	for (; vaddr < vaddr_end; vaddr = next_vaddr) {
914 		int len, s_off, d_off;
915 
916 		/* lock userspace source and destination page */
917 		src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
918 		if (IS_ERR(src_p))
919 			return PTR_ERR(src_p);
920 
921 		dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
922 		if (IS_ERR(dst_p)) {
923 			sev_unpin_memory(kvm, src_p, n);
924 			return PTR_ERR(dst_p);
925 		}
926 
927 		/*
928 		 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify
929 		 * the pages; flush the destination too so that future accesses do not
930 		 * see stale data.
931 		 */
932 		sev_clflush_pages(src_p, 1);
933 		sev_clflush_pages(dst_p, 1);
934 
935 		/*
936 		 * Since user buffer may not be page aligned, calculate the
937 		 * offset within the page.
938 		 */
939 		s_off = vaddr & ~PAGE_MASK;
940 		d_off = dst_vaddr & ~PAGE_MASK;
941 		len = min_t(size_t, (PAGE_SIZE - s_off), size);
942 
943 		if (dec)
944 			ret = __sev_dbg_decrypt_user(kvm,
945 						     __sme_page_pa(src_p[0]) + s_off,
946 						     (void __user *)dst_vaddr,
947 						     __sme_page_pa(dst_p[0]) + d_off,
948 						     len, &argp->error);
949 		else
950 			ret = __sev_dbg_encrypt_user(kvm,
951 						     __sme_page_pa(src_p[0]) + s_off,
952 						     (void __user *)vaddr,
953 						     __sme_page_pa(dst_p[0]) + d_off,
954 						     (void __user *)dst_vaddr,
955 						     len, &argp->error);
956 
957 		sev_unpin_memory(kvm, src_p, n);
958 		sev_unpin_memory(kvm, dst_p, n);
959 
960 		if (ret)
961 			goto err;
962 
963 		next_vaddr = vaddr + len;
964 		dst_vaddr = dst_vaddr + len;
965 		size -= len;
966 	}
967 err:
968 	return ret;
969 }
970 
971 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
972 {
973 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
974 	struct sev_data_launch_secret data;
975 	struct kvm_sev_launch_secret params;
976 	struct page **pages;
977 	void *blob, *hdr;
978 	unsigned long n, i;
979 	int ret, offset;
980 
981 	if (!sev_guest(kvm))
982 		return -ENOTTY;
983 
984 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
985 		return -EFAULT;
986 
987 	pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
988 	if (IS_ERR(pages))
989 		return PTR_ERR(pages);
990 
991 	/*
992 	 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in
993 	 * place; the cache may contain the data that was written unencrypted.
994 	 */
995 	sev_clflush_pages(pages, n);
996 
997 	/*
998 	 * The secret must be copied into contiguous memory region, lets verify
999 	 * that userspace memory pages are contiguous before we issue command.
1000 	 */
1001 	if (get_num_contig_pages(0, pages, n) != n) {
1002 		ret = -EINVAL;
1003 		goto e_unpin_memory;
1004 	}
1005 
1006 	memset(&data, 0, sizeof(data));
1007 
1008 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1009 	data.guest_address = __sme_page_pa(pages[0]) + offset;
1010 	data.guest_len = params.guest_len;
1011 
1012 	blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1013 	if (IS_ERR(blob)) {
1014 		ret = PTR_ERR(blob);
1015 		goto e_unpin_memory;
1016 	}
1017 
1018 	data.trans_address = __psp_pa(blob);
1019 	data.trans_len = params.trans_len;
1020 
1021 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1022 	if (IS_ERR(hdr)) {
1023 		ret = PTR_ERR(hdr);
1024 		goto e_free_blob;
1025 	}
1026 	data.hdr_address = __psp_pa(hdr);
1027 	data.hdr_len = params.hdr_len;
1028 
1029 	data.handle = sev->handle;
1030 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, &data, &argp->error);
1031 
1032 	kfree(hdr);
1033 
1034 e_free_blob:
1035 	kfree(blob);
1036 e_unpin_memory:
1037 	/* content of memory is updated, mark pages dirty */
1038 	for (i = 0; i < n; i++) {
1039 		set_page_dirty_lock(pages[i]);
1040 		mark_page_accessed(pages[i]);
1041 	}
1042 	sev_unpin_memory(kvm, pages, n);
1043 	return ret;
1044 }
1045 
1046 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp)
1047 {
1048 	void __user *report = (void __user *)(uintptr_t)argp->data;
1049 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1050 	struct sev_data_attestation_report data;
1051 	struct kvm_sev_attestation_report params;
1052 	void __user *p;
1053 	void *blob = NULL;
1054 	int ret;
1055 
1056 	if (!sev_guest(kvm))
1057 		return -ENOTTY;
1058 
1059 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
1060 		return -EFAULT;
1061 
1062 	memset(&data, 0, sizeof(data));
1063 
1064 	/* User wants to query the blob length */
1065 	if (!params.len)
1066 		goto cmd;
1067 
1068 	p = (void __user *)(uintptr_t)params.uaddr;
1069 	if (p) {
1070 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
1071 			return -EINVAL;
1072 
1073 		blob = kmalloc(params.len, GFP_KERNEL_ACCOUNT);
1074 		if (!blob)
1075 			return -ENOMEM;
1076 
1077 		data.address = __psp_pa(blob);
1078 		data.len = params.len;
1079 		memcpy(data.mnonce, params.mnonce, sizeof(params.mnonce));
1080 	}
1081 cmd:
1082 	data.handle = sev->handle;
1083 	ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, &data, &argp->error);
1084 	/*
1085 	 * If we query the session length, FW responded with expected data.
1086 	 */
1087 	if (!params.len)
1088 		goto done;
1089 
1090 	if (ret)
1091 		goto e_free_blob;
1092 
1093 	if (blob) {
1094 		if (copy_to_user(p, blob, params.len))
1095 			ret = -EFAULT;
1096 	}
1097 
1098 done:
1099 	params.len = data.len;
1100 	if (copy_to_user(report, &params, sizeof(params)))
1101 		ret = -EFAULT;
1102 e_free_blob:
1103 	kfree(blob);
1104 	return ret;
1105 }
1106 
1107 /* Userspace wants to query session length. */
1108 static int
1109 __sev_send_start_query_session_length(struct kvm *kvm, struct kvm_sev_cmd *argp,
1110 				      struct kvm_sev_send_start *params)
1111 {
1112 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1113 	struct sev_data_send_start data;
1114 	int ret;
1115 
1116 	memset(&data, 0, sizeof(data));
1117 	data.handle = sev->handle;
1118 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1119 
1120 	params->session_len = data.session_len;
1121 	if (copy_to_user((void __user *)(uintptr_t)argp->data, params,
1122 				sizeof(struct kvm_sev_send_start)))
1123 		ret = -EFAULT;
1124 
1125 	return ret;
1126 }
1127 
1128 static int sev_send_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1129 {
1130 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1131 	struct sev_data_send_start data;
1132 	struct kvm_sev_send_start params;
1133 	void *amd_certs, *session_data;
1134 	void *pdh_cert, *plat_certs;
1135 	int ret;
1136 
1137 	if (!sev_guest(kvm))
1138 		return -ENOTTY;
1139 
1140 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1141 				sizeof(struct kvm_sev_send_start)))
1142 		return -EFAULT;
1143 
1144 	/* if session_len is zero, userspace wants to query the session length */
1145 	if (!params.session_len)
1146 		return __sev_send_start_query_session_length(kvm, argp,
1147 				&params);
1148 
1149 	/* some sanity checks */
1150 	if (!params.pdh_cert_uaddr || !params.pdh_cert_len ||
1151 	    !params.session_uaddr || params.session_len > SEV_FW_BLOB_MAX_SIZE)
1152 		return -EINVAL;
1153 
1154 	/* allocate the memory to hold the session data blob */
1155 	session_data = kmalloc(params.session_len, GFP_KERNEL_ACCOUNT);
1156 	if (!session_data)
1157 		return -ENOMEM;
1158 
1159 	/* copy the certificate blobs from userspace */
1160 	pdh_cert = psp_copy_user_blob(params.pdh_cert_uaddr,
1161 				params.pdh_cert_len);
1162 	if (IS_ERR(pdh_cert)) {
1163 		ret = PTR_ERR(pdh_cert);
1164 		goto e_free_session;
1165 	}
1166 
1167 	plat_certs = psp_copy_user_blob(params.plat_certs_uaddr,
1168 				params.plat_certs_len);
1169 	if (IS_ERR(plat_certs)) {
1170 		ret = PTR_ERR(plat_certs);
1171 		goto e_free_pdh;
1172 	}
1173 
1174 	amd_certs = psp_copy_user_blob(params.amd_certs_uaddr,
1175 				params.amd_certs_len);
1176 	if (IS_ERR(amd_certs)) {
1177 		ret = PTR_ERR(amd_certs);
1178 		goto e_free_plat_cert;
1179 	}
1180 
1181 	/* populate the FW SEND_START field with system physical address */
1182 	memset(&data, 0, sizeof(data));
1183 	data.pdh_cert_address = __psp_pa(pdh_cert);
1184 	data.pdh_cert_len = params.pdh_cert_len;
1185 	data.plat_certs_address = __psp_pa(plat_certs);
1186 	data.plat_certs_len = params.plat_certs_len;
1187 	data.amd_certs_address = __psp_pa(amd_certs);
1188 	data.amd_certs_len = params.amd_certs_len;
1189 	data.session_address = __psp_pa(session_data);
1190 	data.session_len = params.session_len;
1191 	data.handle = sev->handle;
1192 
1193 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1194 
1195 	if (!ret && copy_to_user((void __user *)(uintptr_t)params.session_uaddr,
1196 			session_data, params.session_len)) {
1197 		ret = -EFAULT;
1198 		goto e_free_amd_cert;
1199 	}
1200 
1201 	params.policy = data.policy;
1202 	params.session_len = data.session_len;
1203 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params,
1204 				sizeof(struct kvm_sev_send_start)))
1205 		ret = -EFAULT;
1206 
1207 e_free_amd_cert:
1208 	kfree(amd_certs);
1209 e_free_plat_cert:
1210 	kfree(plat_certs);
1211 e_free_pdh:
1212 	kfree(pdh_cert);
1213 e_free_session:
1214 	kfree(session_data);
1215 	return ret;
1216 }
1217 
1218 /* Userspace wants to query either header or trans length. */
1219 static int
1220 __sev_send_update_data_query_lengths(struct kvm *kvm, struct kvm_sev_cmd *argp,
1221 				     struct kvm_sev_send_update_data *params)
1222 {
1223 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1224 	struct sev_data_send_update_data data;
1225 	int ret;
1226 
1227 	memset(&data, 0, sizeof(data));
1228 	data.handle = sev->handle;
1229 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1230 
1231 	params->hdr_len = data.hdr_len;
1232 	params->trans_len = data.trans_len;
1233 
1234 	if (copy_to_user((void __user *)(uintptr_t)argp->data, params,
1235 			 sizeof(struct kvm_sev_send_update_data)))
1236 		ret = -EFAULT;
1237 
1238 	return ret;
1239 }
1240 
1241 static int sev_send_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1242 {
1243 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1244 	struct sev_data_send_update_data data;
1245 	struct kvm_sev_send_update_data params;
1246 	void *hdr, *trans_data;
1247 	struct page **guest_page;
1248 	unsigned long n;
1249 	int ret, offset;
1250 
1251 	if (!sev_guest(kvm))
1252 		return -ENOTTY;
1253 
1254 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1255 			sizeof(struct kvm_sev_send_update_data)))
1256 		return -EFAULT;
1257 
1258 	/* userspace wants to query either header or trans length */
1259 	if (!params.trans_len || !params.hdr_len)
1260 		return __sev_send_update_data_query_lengths(kvm, argp, &params);
1261 
1262 	if (!params.trans_uaddr || !params.guest_uaddr ||
1263 	    !params.guest_len || !params.hdr_uaddr)
1264 		return -EINVAL;
1265 
1266 	/* Check if we are crossing the page boundary */
1267 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1268 	if ((params.guest_len + offset > PAGE_SIZE))
1269 		return -EINVAL;
1270 
1271 	/* Pin guest memory */
1272 	guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1273 				    PAGE_SIZE, &n, 0);
1274 	if (IS_ERR(guest_page))
1275 		return PTR_ERR(guest_page);
1276 
1277 	/* allocate memory for header and transport buffer */
1278 	ret = -ENOMEM;
1279 	hdr = kmalloc(params.hdr_len, GFP_KERNEL_ACCOUNT);
1280 	if (!hdr)
1281 		goto e_unpin;
1282 
1283 	trans_data = kmalloc(params.trans_len, GFP_KERNEL_ACCOUNT);
1284 	if (!trans_data)
1285 		goto e_free_hdr;
1286 
1287 	memset(&data, 0, sizeof(data));
1288 	data.hdr_address = __psp_pa(hdr);
1289 	data.hdr_len = params.hdr_len;
1290 	data.trans_address = __psp_pa(trans_data);
1291 	data.trans_len = params.trans_len;
1292 
1293 	/* The SEND_UPDATE_DATA command requires C-bit to be always set. */
1294 	data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1295 	data.guest_address |= sev_me_mask;
1296 	data.guest_len = params.guest_len;
1297 	data.handle = sev->handle;
1298 
1299 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1300 
1301 	if (ret)
1302 		goto e_free_trans_data;
1303 
1304 	/* copy transport buffer to user space */
1305 	if (copy_to_user((void __user *)(uintptr_t)params.trans_uaddr,
1306 			 trans_data, params.trans_len)) {
1307 		ret = -EFAULT;
1308 		goto e_free_trans_data;
1309 	}
1310 
1311 	/* Copy packet header to userspace. */
1312 	if (copy_to_user((void __user *)(uintptr_t)params.hdr_uaddr, hdr,
1313 			 params.hdr_len))
1314 		ret = -EFAULT;
1315 
1316 e_free_trans_data:
1317 	kfree(trans_data);
1318 e_free_hdr:
1319 	kfree(hdr);
1320 e_unpin:
1321 	sev_unpin_memory(kvm, guest_page, n);
1322 
1323 	return ret;
1324 }
1325 
1326 static int sev_send_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1327 {
1328 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1329 	struct sev_data_send_finish data;
1330 
1331 	if (!sev_guest(kvm))
1332 		return -ENOTTY;
1333 
1334 	data.handle = sev->handle;
1335 	return sev_issue_cmd(kvm, SEV_CMD_SEND_FINISH, &data, &argp->error);
1336 }
1337 
1338 static int sev_send_cancel(struct kvm *kvm, struct kvm_sev_cmd *argp)
1339 {
1340 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1341 	struct sev_data_send_cancel data;
1342 
1343 	if (!sev_guest(kvm))
1344 		return -ENOTTY;
1345 
1346 	data.handle = sev->handle;
1347 	return sev_issue_cmd(kvm, SEV_CMD_SEND_CANCEL, &data, &argp->error);
1348 }
1349 
1350 static int sev_receive_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1351 {
1352 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1353 	struct sev_data_receive_start start;
1354 	struct kvm_sev_receive_start params;
1355 	int *error = &argp->error;
1356 	void *session_data;
1357 	void *pdh_data;
1358 	int ret;
1359 
1360 	if (!sev_guest(kvm))
1361 		return -ENOTTY;
1362 
1363 	/* Get parameter from the userspace */
1364 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1365 			sizeof(struct kvm_sev_receive_start)))
1366 		return -EFAULT;
1367 
1368 	/* some sanity checks */
1369 	if (!params.pdh_uaddr || !params.pdh_len ||
1370 	    !params.session_uaddr || !params.session_len)
1371 		return -EINVAL;
1372 
1373 	pdh_data = psp_copy_user_blob(params.pdh_uaddr, params.pdh_len);
1374 	if (IS_ERR(pdh_data))
1375 		return PTR_ERR(pdh_data);
1376 
1377 	session_data = psp_copy_user_blob(params.session_uaddr,
1378 			params.session_len);
1379 	if (IS_ERR(session_data)) {
1380 		ret = PTR_ERR(session_data);
1381 		goto e_free_pdh;
1382 	}
1383 
1384 	memset(&start, 0, sizeof(start));
1385 	start.handle = params.handle;
1386 	start.policy = params.policy;
1387 	start.pdh_cert_address = __psp_pa(pdh_data);
1388 	start.pdh_cert_len = params.pdh_len;
1389 	start.session_address = __psp_pa(session_data);
1390 	start.session_len = params.session_len;
1391 
1392 	/* create memory encryption context */
1393 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_RECEIVE_START, &start,
1394 				error);
1395 	if (ret)
1396 		goto e_free_session;
1397 
1398 	/* Bind ASID to this guest */
1399 	ret = sev_bind_asid(kvm, start.handle, error);
1400 	if (ret)
1401 		goto e_free_session;
1402 
1403 	params.handle = start.handle;
1404 	if (copy_to_user((void __user *)(uintptr_t)argp->data,
1405 			 &params, sizeof(struct kvm_sev_receive_start))) {
1406 		ret = -EFAULT;
1407 		sev_unbind_asid(kvm, start.handle);
1408 		goto e_free_session;
1409 	}
1410 
1411     	sev->handle = start.handle;
1412 	sev->fd = argp->sev_fd;
1413 
1414 e_free_session:
1415 	kfree(session_data);
1416 e_free_pdh:
1417 	kfree(pdh_data);
1418 
1419 	return ret;
1420 }
1421 
1422 static int sev_receive_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1423 {
1424 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1425 	struct kvm_sev_receive_update_data params;
1426 	struct sev_data_receive_update_data data;
1427 	void *hdr = NULL, *trans = NULL;
1428 	struct page **guest_page;
1429 	unsigned long n;
1430 	int ret, offset;
1431 
1432 	if (!sev_guest(kvm))
1433 		return -EINVAL;
1434 
1435 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1436 			sizeof(struct kvm_sev_receive_update_data)))
1437 		return -EFAULT;
1438 
1439 	if (!params.hdr_uaddr || !params.hdr_len ||
1440 	    !params.guest_uaddr || !params.guest_len ||
1441 	    !params.trans_uaddr || !params.trans_len)
1442 		return -EINVAL;
1443 
1444 	/* Check if we are crossing the page boundary */
1445 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1446 	if ((params.guest_len + offset > PAGE_SIZE))
1447 		return -EINVAL;
1448 
1449 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1450 	if (IS_ERR(hdr))
1451 		return PTR_ERR(hdr);
1452 
1453 	trans = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1454 	if (IS_ERR(trans)) {
1455 		ret = PTR_ERR(trans);
1456 		goto e_free_hdr;
1457 	}
1458 
1459 	memset(&data, 0, sizeof(data));
1460 	data.hdr_address = __psp_pa(hdr);
1461 	data.hdr_len = params.hdr_len;
1462 	data.trans_address = __psp_pa(trans);
1463 	data.trans_len = params.trans_len;
1464 
1465 	/* Pin guest memory */
1466 	guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1467 				    PAGE_SIZE, &n, 0);
1468 	if (IS_ERR(guest_page)) {
1469 		ret = PTR_ERR(guest_page);
1470 		goto e_free_trans;
1471 	}
1472 
1473 	/* The RECEIVE_UPDATE_DATA command requires C-bit to be always set. */
1474 	data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1475 	data.guest_address |= sev_me_mask;
1476 	data.guest_len = params.guest_len;
1477 	data.handle = sev->handle;
1478 
1479 	ret = sev_issue_cmd(kvm, SEV_CMD_RECEIVE_UPDATE_DATA, &data,
1480 				&argp->error);
1481 
1482 	sev_unpin_memory(kvm, guest_page, n);
1483 
1484 e_free_trans:
1485 	kfree(trans);
1486 e_free_hdr:
1487 	kfree(hdr);
1488 
1489 	return ret;
1490 }
1491 
1492 static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1493 {
1494 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1495 	struct sev_data_receive_finish data;
1496 
1497 	if (!sev_guest(kvm))
1498 		return -ENOTTY;
1499 
1500 	data.handle = sev->handle;
1501 	return sev_issue_cmd(kvm, SEV_CMD_RECEIVE_FINISH, &data, &argp->error);
1502 }
1503 
1504 int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
1505 {
1506 	struct kvm_sev_cmd sev_cmd;
1507 	int r;
1508 
1509 	if (!sev_enabled)
1510 		return -ENOTTY;
1511 
1512 	if (!argp)
1513 		return 0;
1514 
1515 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
1516 		return -EFAULT;
1517 
1518 	mutex_lock(&kvm->lock);
1519 
1520 	/* enc_context_owner handles all memory enc operations */
1521 	if (is_mirroring_enc_context(kvm)) {
1522 		r = -EINVAL;
1523 		goto out;
1524 	}
1525 
1526 	switch (sev_cmd.id) {
1527 	case KVM_SEV_ES_INIT:
1528 		if (!sev_es_enabled) {
1529 			r = -ENOTTY;
1530 			goto out;
1531 		}
1532 		fallthrough;
1533 	case KVM_SEV_INIT:
1534 		r = sev_guest_init(kvm, &sev_cmd);
1535 		break;
1536 	case KVM_SEV_LAUNCH_START:
1537 		r = sev_launch_start(kvm, &sev_cmd);
1538 		break;
1539 	case KVM_SEV_LAUNCH_UPDATE_DATA:
1540 		r = sev_launch_update_data(kvm, &sev_cmd);
1541 		break;
1542 	case KVM_SEV_LAUNCH_UPDATE_VMSA:
1543 		r = sev_launch_update_vmsa(kvm, &sev_cmd);
1544 		break;
1545 	case KVM_SEV_LAUNCH_MEASURE:
1546 		r = sev_launch_measure(kvm, &sev_cmd);
1547 		break;
1548 	case KVM_SEV_LAUNCH_FINISH:
1549 		r = sev_launch_finish(kvm, &sev_cmd);
1550 		break;
1551 	case KVM_SEV_GUEST_STATUS:
1552 		r = sev_guest_status(kvm, &sev_cmd);
1553 		break;
1554 	case KVM_SEV_DBG_DECRYPT:
1555 		r = sev_dbg_crypt(kvm, &sev_cmd, true);
1556 		break;
1557 	case KVM_SEV_DBG_ENCRYPT:
1558 		r = sev_dbg_crypt(kvm, &sev_cmd, false);
1559 		break;
1560 	case KVM_SEV_LAUNCH_SECRET:
1561 		r = sev_launch_secret(kvm, &sev_cmd);
1562 		break;
1563 	case KVM_SEV_GET_ATTESTATION_REPORT:
1564 		r = sev_get_attestation_report(kvm, &sev_cmd);
1565 		break;
1566 	case KVM_SEV_SEND_START:
1567 		r = sev_send_start(kvm, &sev_cmd);
1568 		break;
1569 	case KVM_SEV_SEND_UPDATE_DATA:
1570 		r = sev_send_update_data(kvm, &sev_cmd);
1571 		break;
1572 	case KVM_SEV_SEND_FINISH:
1573 		r = sev_send_finish(kvm, &sev_cmd);
1574 		break;
1575 	case KVM_SEV_SEND_CANCEL:
1576 		r = sev_send_cancel(kvm, &sev_cmd);
1577 		break;
1578 	case KVM_SEV_RECEIVE_START:
1579 		r = sev_receive_start(kvm, &sev_cmd);
1580 		break;
1581 	case KVM_SEV_RECEIVE_UPDATE_DATA:
1582 		r = sev_receive_update_data(kvm, &sev_cmd);
1583 		break;
1584 	case KVM_SEV_RECEIVE_FINISH:
1585 		r = sev_receive_finish(kvm, &sev_cmd);
1586 		break;
1587 	default:
1588 		r = -EINVAL;
1589 		goto out;
1590 	}
1591 
1592 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
1593 		r = -EFAULT;
1594 
1595 out:
1596 	mutex_unlock(&kvm->lock);
1597 	return r;
1598 }
1599 
1600 int svm_register_enc_region(struct kvm *kvm,
1601 			    struct kvm_enc_region *range)
1602 {
1603 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1604 	struct enc_region *region;
1605 	int ret = 0;
1606 
1607 	if (!sev_guest(kvm))
1608 		return -ENOTTY;
1609 
1610 	/* If kvm is mirroring encryption context it isn't responsible for it */
1611 	if (is_mirroring_enc_context(kvm))
1612 		return -EINVAL;
1613 
1614 	if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
1615 		return -EINVAL;
1616 
1617 	region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
1618 	if (!region)
1619 		return -ENOMEM;
1620 
1621 	mutex_lock(&kvm->lock);
1622 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
1623 	if (IS_ERR(region->pages)) {
1624 		ret = PTR_ERR(region->pages);
1625 		mutex_unlock(&kvm->lock);
1626 		goto e_free;
1627 	}
1628 
1629 	region->uaddr = range->addr;
1630 	region->size = range->size;
1631 
1632 	list_add_tail(&region->list, &sev->regions_list);
1633 	mutex_unlock(&kvm->lock);
1634 
1635 	/*
1636 	 * The guest may change the memory encryption attribute from C=0 -> C=1
1637 	 * or vice versa for this memory range. Lets make sure caches are
1638 	 * flushed to ensure that guest data gets written into memory with
1639 	 * correct C-bit.
1640 	 */
1641 	sev_clflush_pages(region->pages, region->npages);
1642 
1643 	return ret;
1644 
1645 e_free:
1646 	kfree(region);
1647 	return ret;
1648 }
1649 
1650 static struct enc_region *
1651 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
1652 {
1653 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1654 	struct list_head *head = &sev->regions_list;
1655 	struct enc_region *i;
1656 
1657 	list_for_each_entry(i, head, list) {
1658 		if (i->uaddr == range->addr &&
1659 		    i->size == range->size)
1660 			return i;
1661 	}
1662 
1663 	return NULL;
1664 }
1665 
1666 static void __unregister_enc_region_locked(struct kvm *kvm,
1667 					   struct enc_region *region)
1668 {
1669 	sev_unpin_memory(kvm, region->pages, region->npages);
1670 	list_del(&region->list);
1671 	kfree(region);
1672 }
1673 
1674 int svm_unregister_enc_region(struct kvm *kvm,
1675 			      struct kvm_enc_region *range)
1676 {
1677 	struct enc_region *region;
1678 	int ret;
1679 
1680 	/* If kvm is mirroring encryption context it isn't responsible for it */
1681 	if (is_mirroring_enc_context(kvm))
1682 		return -EINVAL;
1683 
1684 	mutex_lock(&kvm->lock);
1685 
1686 	if (!sev_guest(kvm)) {
1687 		ret = -ENOTTY;
1688 		goto failed;
1689 	}
1690 
1691 	region = find_enc_region(kvm, range);
1692 	if (!region) {
1693 		ret = -EINVAL;
1694 		goto failed;
1695 	}
1696 
1697 	/*
1698 	 * Ensure that all guest tagged cache entries are flushed before
1699 	 * releasing the pages back to the system for use. CLFLUSH will
1700 	 * not do this, so issue a WBINVD.
1701 	 */
1702 	wbinvd_on_all_cpus();
1703 
1704 	__unregister_enc_region_locked(kvm, region);
1705 
1706 	mutex_unlock(&kvm->lock);
1707 	return 0;
1708 
1709 failed:
1710 	mutex_unlock(&kvm->lock);
1711 	return ret;
1712 }
1713 
1714 int svm_vm_copy_asid_from(struct kvm *kvm, unsigned int source_fd)
1715 {
1716 	struct file *source_kvm_file;
1717 	struct kvm *source_kvm;
1718 	struct kvm_sev_info *mirror_sev;
1719 	unsigned int asid;
1720 	int ret;
1721 
1722 	source_kvm_file = fget(source_fd);
1723 	if (!file_is_kvm(source_kvm_file)) {
1724 		ret = -EBADF;
1725 		goto e_source_put;
1726 	}
1727 
1728 	source_kvm = source_kvm_file->private_data;
1729 	mutex_lock(&source_kvm->lock);
1730 
1731 	if (!sev_guest(source_kvm)) {
1732 		ret = -EINVAL;
1733 		goto e_source_unlock;
1734 	}
1735 
1736 	/* Mirrors of mirrors should work, but let's not get silly */
1737 	if (is_mirroring_enc_context(source_kvm) || source_kvm == kvm) {
1738 		ret = -EINVAL;
1739 		goto e_source_unlock;
1740 	}
1741 
1742 	asid = to_kvm_svm(source_kvm)->sev_info.asid;
1743 
1744 	/*
1745 	 * The mirror kvm holds an enc_context_owner ref so its asid can't
1746 	 * disappear until we're done with it
1747 	 */
1748 	kvm_get_kvm(source_kvm);
1749 
1750 	fput(source_kvm_file);
1751 	mutex_unlock(&source_kvm->lock);
1752 	mutex_lock(&kvm->lock);
1753 
1754 	if (sev_guest(kvm)) {
1755 		ret = -EINVAL;
1756 		goto e_mirror_unlock;
1757 	}
1758 
1759 	/* Set enc_context_owner and copy its encryption context over */
1760 	mirror_sev = &to_kvm_svm(kvm)->sev_info;
1761 	mirror_sev->enc_context_owner = source_kvm;
1762 	mirror_sev->asid = asid;
1763 	mirror_sev->active = true;
1764 
1765 	mutex_unlock(&kvm->lock);
1766 	return 0;
1767 
1768 e_mirror_unlock:
1769 	mutex_unlock(&kvm->lock);
1770 	kvm_put_kvm(source_kvm);
1771 	return ret;
1772 e_source_unlock:
1773 	mutex_unlock(&source_kvm->lock);
1774 e_source_put:
1775 	if (source_kvm_file)
1776 		fput(source_kvm_file);
1777 	return ret;
1778 }
1779 
1780 void sev_vm_destroy(struct kvm *kvm)
1781 {
1782 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1783 	struct list_head *head = &sev->regions_list;
1784 	struct list_head *pos, *q;
1785 
1786 	if (!sev_guest(kvm))
1787 		return;
1788 
1789 	/* If this is a mirror_kvm release the enc_context_owner and skip sev cleanup */
1790 	if (is_mirroring_enc_context(kvm)) {
1791 		kvm_put_kvm(sev->enc_context_owner);
1792 		return;
1793 	}
1794 
1795 	mutex_lock(&kvm->lock);
1796 
1797 	/*
1798 	 * Ensure that all guest tagged cache entries are flushed before
1799 	 * releasing the pages back to the system for use. CLFLUSH will
1800 	 * not do this, so issue a WBINVD.
1801 	 */
1802 	wbinvd_on_all_cpus();
1803 
1804 	/*
1805 	 * if userspace was terminated before unregistering the memory regions
1806 	 * then lets unpin all the registered memory.
1807 	 */
1808 	if (!list_empty(head)) {
1809 		list_for_each_safe(pos, q, head) {
1810 			__unregister_enc_region_locked(kvm,
1811 				list_entry(pos, struct enc_region, list));
1812 			cond_resched();
1813 		}
1814 	}
1815 
1816 	mutex_unlock(&kvm->lock);
1817 
1818 	sev_unbind_asid(kvm, sev->handle);
1819 	sev_asid_free(sev);
1820 }
1821 
1822 void __init sev_set_cpu_caps(void)
1823 {
1824 	if (!sev_enabled)
1825 		kvm_cpu_cap_clear(X86_FEATURE_SEV);
1826 	if (!sev_es_enabled)
1827 		kvm_cpu_cap_clear(X86_FEATURE_SEV_ES);
1828 }
1829 
1830 void __init sev_hardware_setup(void)
1831 {
1832 #ifdef CONFIG_KVM_AMD_SEV
1833 	unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count;
1834 	bool sev_es_supported = false;
1835 	bool sev_supported = false;
1836 
1837 	if (!sev_enabled || !npt_enabled)
1838 		goto out;
1839 
1840 	/* Does the CPU support SEV? */
1841 	if (!boot_cpu_has(X86_FEATURE_SEV))
1842 		goto out;
1843 
1844 	/* Retrieve SEV CPUID information */
1845 	cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
1846 
1847 	/* Set encryption bit location for SEV-ES guests */
1848 	sev_enc_bit = ebx & 0x3f;
1849 
1850 	/* Maximum number of encrypted guests supported simultaneously */
1851 	max_sev_asid = ecx;
1852 	if (!max_sev_asid)
1853 		goto out;
1854 
1855 	/* Minimum ASID value that should be used for SEV guest */
1856 	min_sev_asid = edx;
1857 	sev_me_mask = 1UL << (ebx & 0x3f);
1858 
1859 	/*
1860 	 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap,
1861 	 * even though it's never used, so that the bitmap is indexed by the
1862 	 * actual ASID.
1863 	 */
1864 	nr_asids = max_sev_asid + 1;
1865 	sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
1866 	if (!sev_asid_bitmap)
1867 		goto out;
1868 
1869 	sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
1870 	if (!sev_reclaim_asid_bitmap) {
1871 		bitmap_free(sev_asid_bitmap);
1872 		sev_asid_bitmap = NULL;
1873 		goto out;
1874 	}
1875 
1876 	sev_asid_count = max_sev_asid - min_sev_asid + 1;
1877 	if (misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count))
1878 		goto out;
1879 
1880 	pr_info("SEV supported: %u ASIDs\n", sev_asid_count);
1881 	sev_supported = true;
1882 
1883 	/* SEV-ES support requested? */
1884 	if (!sev_es_enabled)
1885 		goto out;
1886 
1887 	/* Does the CPU support SEV-ES? */
1888 	if (!boot_cpu_has(X86_FEATURE_SEV_ES))
1889 		goto out;
1890 
1891 	/* Has the system been allocated ASIDs for SEV-ES? */
1892 	if (min_sev_asid == 1)
1893 		goto out;
1894 
1895 	sev_es_asid_count = min_sev_asid - 1;
1896 	if (misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count))
1897 		goto out;
1898 
1899 	pr_info("SEV-ES supported: %u ASIDs\n", sev_es_asid_count);
1900 	sev_es_supported = true;
1901 
1902 out:
1903 	sev_enabled = sev_supported;
1904 	sev_es_enabled = sev_es_supported;
1905 #endif
1906 }
1907 
1908 void sev_hardware_teardown(void)
1909 {
1910 	if (!sev_enabled)
1911 		return;
1912 
1913 	/* No need to take sev_bitmap_lock, all VMs have been destroyed. */
1914 	sev_flush_asids(1, max_sev_asid);
1915 
1916 	bitmap_free(sev_asid_bitmap);
1917 	bitmap_free(sev_reclaim_asid_bitmap);
1918 
1919 	misc_cg_set_capacity(MISC_CG_RES_SEV, 0);
1920 	misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0);
1921 }
1922 
1923 int sev_cpu_init(struct svm_cpu_data *sd)
1924 {
1925 	if (!sev_enabled)
1926 		return 0;
1927 
1928 	sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL);
1929 	if (!sd->sev_vmcbs)
1930 		return -ENOMEM;
1931 
1932 	return 0;
1933 }
1934 
1935 /*
1936  * Pages used by hardware to hold guest encrypted state must be flushed before
1937  * returning them to the system.
1938  */
1939 static void sev_flush_guest_memory(struct vcpu_svm *svm, void *va,
1940 				   unsigned long len)
1941 {
1942 	/*
1943 	 * If hardware enforced cache coherency for encrypted mappings of the
1944 	 * same physical page is supported, nothing to do.
1945 	 */
1946 	if (boot_cpu_has(X86_FEATURE_SME_COHERENT))
1947 		return;
1948 
1949 	/*
1950 	 * If the VM Page Flush MSR is supported, use it to flush the page
1951 	 * (using the page virtual address and the guest ASID).
1952 	 */
1953 	if (boot_cpu_has(X86_FEATURE_VM_PAGE_FLUSH)) {
1954 		struct kvm_sev_info *sev;
1955 		unsigned long va_start;
1956 		u64 start, stop;
1957 
1958 		/* Align start and stop to page boundaries. */
1959 		va_start = (unsigned long)va;
1960 		start = (u64)va_start & PAGE_MASK;
1961 		stop = PAGE_ALIGN((u64)va_start + len);
1962 
1963 		if (start < stop) {
1964 			sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
1965 
1966 			while (start < stop) {
1967 				wrmsrl(MSR_AMD64_VM_PAGE_FLUSH,
1968 				       start | sev->asid);
1969 
1970 				start += PAGE_SIZE;
1971 			}
1972 
1973 			return;
1974 		}
1975 
1976 		WARN(1, "Address overflow, using WBINVD\n");
1977 	}
1978 
1979 	/*
1980 	 * Hardware should always have one of the above features,
1981 	 * but if not, use WBINVD and issue a warning.
1982 	 */
1983 	WARN_ONCE(1, "Using WBINVD to flush guest memory\n");
1984 	wbinvd_on_all_cpus();
1985 }
1986 
1987 void sev_free_vcpu(struct kvm_vcpu *vcpu)
1988 {
1989 	struct vcpu_svm *svm;
1990 
1991 	if (!sev_es_guest(vcpu->kvm))
1992 		return;
1993 
1994 	svm = to_svm(vcpu);
1995 
1996 	if (vcpu->arch.guest_state_protected)
1997 		sev_flush_guest_memory(svm, svm->vmsa, PAGE_SIZE);
1998 	__free_page(virt_to_page(svm->vmsa));
1999 
2000 	if (svm->ghcb_sa_free)
2001 		kfree(svm->ghcb_sa);
2002 }
2003 
2004 static void dump_ghcb(struct vcpu_svm *svm)
2005 {
2006 	struct ghcb *ghcb = svm->ghcb;
2007 	unsigned int nbits;
2008 
2009 	/* Re-use the dump_invalid_vmcb module parameter */
2010 	if (!dump_invalid_vmcb) {
2011 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
2012 		return;
2013 	}
2014 
2015 	nbits = sizeof(ghcb->save.valid_bitmap) * 8;
2016 
2017 	pr_err("GHCB (GPA=%016llx):\n", svm->vmcb->control.ghcb_gpa);
2018 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
2019 	       ghcb->save.sw_exit_code, ghcb_sw_exit_code_is_valid(ghcb));
2020 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
2021 	       ghcb->save.sw_exit_info_1, ghcb_sw_exit_info_1_is_valid(ghcb));
2022 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
2023 	       ghcb->save.sw_exit_info_2, ghcb_sw_exit_info_2_is_valid(ghcb));
2024 	pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
2025 	       ghcb->save.sw_scratch, ghcb_sw_scratch_is_valid(ghcb));
2026 	pr_err("%-20s%*pb\n", "valid_bitmap", nbits, ghcb->save.valid_bitmap);
2027 }
2028 
2029 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
2030 {
2031 	struct kvm_vcpu *vcpu = &svm->vcpu;
2032 	struct ghcb *ghcb = svm->ghcb;
2033 
2034 	/*
2035 	 * The GHCB protocol so far allows for the following data
2036 	 * to be returned:
2037 	 *   GPRs RAX, RBX, RCX, RDX
2038 	 *
2039 	 * Copy their values, even if they may not have been written during the
2040 	 * VM-Exit.  It's the guest's responsibility to not consume random data.
2041 	 */
2042 	ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
2043 	ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
2044 	ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
2045 	ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
2046 }
2047 
2048 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
2049 {
2050 	struct vmcb_control_area *control = &svm->vmcb->control;
2051 	struct kvm_vcpu *vcpu = &svm->vcpu;
2052 	struct ghcb *ghcb = svm->ghcb;
2053 	u64 exit_code;
2054 
2055 	/*
2056 	 * The GHCB protocol so far allows for the following data
2057 	 * to be supplied:
2058 	 *   GPRs RAX, RBX, RCX, RDX
2059 	 *   XCR0
2060 	 *   CPL
2061 	 *
2062 	 * VMMCALL allows the guest to provide extra registers. KVM also
2063 	 * expects RSI for hypercalls, so include that, too.
2064 	 *
2065 	 * Copy their values to the appropriate location if supplied.
2066 	 */
2067 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
2068 
2069 	vcpu->arch.regs[VCPU_REGS_RAX] = ghcb_get_rax_if_valid(ghcb);
2070 	vcpu->arch.regs[VCPU_REGS_RBX] = ghcb_get_rbx_if_valid(ghcb);
2071 	vcpu->arch.regs[VCPU_REGS_RCX] = ghcb_get_rcx_if_valid(ghcb);
2072 	vcpu->arch.regs[VCPU_REGS_RDX] = ghcb_get_rdx_if_valid(ghcb);
2073 	vcpu->arch.regs[VCPU_REGS_RSI] = ghcb_get_rsi_if_valid(ghcb);
2074 
2075 	svm->vmcb->save.cpl = ghcb_get_cpl_if_valid(ghcb);
2076 
2077 	if (ghcb_xcr0_is_valid(ghcb)) {
2078 		vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb);
2079 		kvm_update_cpuid_runtime(vcpu);
2080 	}
2081 
2082 	/* Copy the GHCB exit information into the VMCB fields */
2083 	exit_code = ghcb_get_sw_exit_code(ghcb);
2084 	control->exit_code = lower_32_bits(exit_code);
2085 	control->exit_code_hi = upper_32_bits(exit_code);
2086 	control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb);
2087 	control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb);
2088 
2089 	/* Clear the valid entries fields */
2090 	memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
2091 }
2092 
2093 static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
2094 {
2095 	struct kvm_vcpu *vcpu;
2096 	struct ghcb *ghcb;
2097 	u64 exit_code = 0;
2098 
2099 	ghcb = svm->ghcb;
2100 
2101 	/* Only GHCB Usage code 0 is supported */
2102 	if (ghcb->ghcb_usage)
2103 		goto vmgexit_err;
2104 
2105 	/*
2106 	 * Retrieve the exit code now even though is may not be marked valid
2107 	 * as it could help with debugging.
2108 	 */
2109 	exit_code = ghcb_get_sw_exit_code(ghcb);
2110 
2111 	if (!ghcb_sw_exit_code_is_valid(ghcb) ||
2112 	    !ghcb_sw_exit_info_1_is_valid(ghcb) ||
2113 	    !ghcb_sw_exit_info_2_is_valid(ghcb))
2114 		goto vmgexit_err;
2115 
2116 	switch (ghcb_get_sw_exit_code(ghcb)) {
2117 	case SVM_EXIT_READ_DR7:
2118 		break;
2119 	case SVM_EXIT_WRITE_DR7:
2120 		if (!ghcb_rax_is_valid(ghcb))
2121 			goto vmgexit_err;
2122 		break;
2123 	case SVM_EXIT_RDTSC:
2124 		break;
2125 	case SVM_EXIT_RDPMC:
2126 		if (!ghcb_rcx_is_valid(ghcb))
2127 			goto vmgexit_err;
2128 		break;
2129 	case SVM_EXIT_CPUID:
2130 		if (!ghcb_rax_is_valid(ghcb) ||
2131 		    !ghcb_rcx_is_valid(ghcb))
2132 			goto vmgexit_err;
2133 		if (ghcb_get_rax(ghcb) == 0xd)
2134 			if (!ghcb_xcr0_is_valid(ghcb))
2135 				goto vmgexit_err;
2136 		break;
2137 	case SVM_EXIT_INVD:
2138 		break;
2139 	case SVM_EXIT_IOIO:
2140 		if (ghcb_get_sw_exit_info_1(ghcb) & SVM_IOIO_STR_MASK) {
2141 			if (!ghcb_sw_scratch_is_valid(ghcb))
2142 				goto vmgexit_err;
2143 		} else {
2144 			if (!(ghcb_get_sw_exit_info_1(ghcb) & SVM_IOIO_TYPE_MASK))
2145 				if (!ghcb_rax_is_valid(ghcb))
2146 					goto vmgexit_err;
2147 		}
2148 		break;
2149 	case SVM_EXIT_MSR:
2150 		if (!ghcb_rcx_is_valid(ghcb))
2151 			goto vmgexit_err;
2152 		if (ghcb_get_sw_exit_info_1(ghcb)) {
2153 			if (!ghcb_rax_is_valid(ghcb) ||
2154 			    !ghcb_rdx_is_valid(ghcb))
2155 				goto vmgexit_err;
2156 		}
2157 		break;
2158 	case SVM_EXIT_VMMCALL:
2159 		if (!ghcb_rax_is_valid(ghcb) ||
2160 		    !ghcb_cpl_is_valid(ghcb))
2161 			goto vmgexit_err;
2162 		break;
2163 	case SVM_EXIT_RDTSCP:
2164 		break;
2165 	case SVM_EXIT_WBINVD:
2166 		break;
2167 	case SVM_EXIT_MONITOR:
2168 		if (!ghcb_rax_is_valid(ghcb) ||
2169 		    !ghcb_rcx_is_valid(ghcb) ||
2170 		    !ghcb_rdx_is_valid(ghcb))
2171 			goto vmgexit_err;
2172 		break;
2173 	case SVM_EXIT_MWAIT:
2174 		if (!ghcb_rax_is_valid(ghcb) ||
2175 		    !ghcb_rcx_is_valid(ghcb))
2176 			goto vmgexit_err;
2177 		break;
2178 	case SVM_VMGEXIT_MMIO_READ:
2179 	case SVM_VMGEXIT_MMIO_WRITE:
2180 		if (!ghcb_sw_scratch_is_valid(ghcb))
2181 			goto vmgexit_err;
2182 		break;
2183 	case SVM_VMGEXIT_NMI_COMPLETE:
2184 	case SVM_VMGEXIT_AP_HLT_LOOP:
2185 	case SVM_VMGEXIT_AP_JUMP_TABLE:
2186 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
2187 		break;
2188 	default:
2189 		goto vmgexit_err;
2190 	}
2191 
2192 	return 0;
2193 
2194 vmgexit_err:
2195 	vcpu = &svm->vcpu;
2196 
2197 	if (ghcb->ghcb_usage) {
2198 		vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
2199 			    ghcb->ghcb_usage);
2200 	} else {
2201 		vcpu_unimpl(vcpu, "vmgexit: exit reason %#llx is not valid\n",
2202 			    exit_code);
2203 		dump_ghcb(svm);
2204 	}
2205 
2206 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2207 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
2208 	vcpu->run->internal.ndata = 2;
2209 	vcpu->run->internal.data[0] = exit_code;
2210 	vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
2211 
2212 	return -EINVAL;
2213 }
2214 
2215 void sev_es_unmap_ghcb(struct vcpu_svm *svm)
2216 {
2217 	if (!svm->ghcb)
2218 		return;
2219 
2220 	if (svm->ghcb_sa_free) {
2221 		/*
2222 		 * The scratch area lives outside the GHCB, so there is a
2223 		 * buffer that, depending on the operation performed, may
2224 		 * need to be synced, then freed.
2225 		 */
2226 		if (svm->ghcb_sa_sync) {
2227 			kvm_write_guest(svm->vcpu.kvm,
2228 					ghcb_get_sw_scratch(svm->ghcb),
2229 					svm->ghcb_sa, svm->ghcb_sa_len);
2230 			svm->ghcb_sa_sync = false;
2231 		}
2232 
2233 		kfree(svm->ghcb_sa);
2234 		svm->ghcb_sa = NULL;
2235 		svm->ghcb_sa_free = false;
2236 	}
2237 
2238 	trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->ghcb);
2239 
2240 	sev_es_sync_to_ghcb(svm);
2241 
2242 	kvm_vcpu_unmap(&svm->vcpu, &svm->ghcb_map, true);
2243 	svm->ghcb = NULL;
2244 }
2245 
2246 void pre_sev_run(struct vcpu_svm *svm, int cpu)
2247 {
2248 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2249 	int asid = sev_get_asid(svm->vcpu.kvm);
2250 
2251 	/* Assign the asid allocated with this SEV guest */
2252 	svm->asid = asid;
2253 
2254 	/*
2255 	 * Flush guest TLB:
2256 	 *
2257 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
2258 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
2259 	 */
2260 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
2261 	    svm->vcpu.arch.last_vmentry_cpu == cpu)
2262 		return;
2263 
2264 	sd->sev_vmcbs[asid] = svm->vmcb;
2265 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
2266 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
2267 }
2268 
2269 #define GHCB_SCRATCH_AREA_LIMIT		(16ULL * PAGE_SIZE)
2270 static bool setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len)
2271 {
2272 	struct vmcb_control_area *control = &svm->vmcb->control;
2273 	struct ghcb *ghcb = svm->ghcb;
2274 	u64 ghcb_scratch_beg, ghcb_scratch_end;
2275 	u64 scratch_gpa_beg, scratch_gpa_end;
2276 	void *scratch_va;
2277 
2278 	scratch_gpa_beg = ghcb_get_sw_scratch(ghcb);
2279 	if (!scratch_gpa_beg) {
2280 		pr_err("vmgexit: scratch gpa not provided\n");
2281 		return false;
2282 	}
2283 
2284 	scratch_gpa_end = scratch_gpa_beg + len;
2285 	if (scratch_gpa_end < scratch_gpa_beg) {
2286 		pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
2287 		       len, scratch_gpa_beg);
2288 		return false;
2289 	}
2290 
2291 	if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
2292 		/* Scratch area begins within GHCB */
2293 		ghcb_scratch_beg = control->ghcb_gpa +
2294 				   offsetof(struct ghcb, shared_buffer);
2295 		ghcb_scratch_end = control->ghcb_gpa +
2296 				   offsetof(struct ghcb, reserved_1);
2297 
2298 		/*
2299 		 * If the scratch area begins within the GHCB, it must be
2300 		 * completely contained in the GHCB shared buffer area.
2301 		 */
2302 		if (scratch_gpa_beg < ghcb_scratch_beg ||
2303 		    scratch_gpa_end > ghcb_scratch_end) {
2304 			pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
2305 			       scratch_gpa_beg, scratch_gpa_end);
2306 			return false;
2307 		}
2308 
2309 		scratch_va = (void *)svm->ghcb;
2310 		scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
2311 	} else {
2312 		/*
2313 		 * The guest memory must be read into a kernel buffer, so
2314 		 * limit the size
2315 		 */
2316 		if (len > GHCB_SCRATCH_AREA_LIMIT) {
2317 			pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
2318 			       len, GHCB_SCRATCH_AREA_LIMIT);
2319 			return false;
2320 		}
2321 		scratch_va = kzalloc(len, GFP_KERNEL_ACCOUNT);
2322 		if (!scratch_va)
2323 			return false;
2324 
2325 		if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) {
2326 			/* Unable to copy scratch area from guest */
2327 			pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
2328 
2329 			kfree(scratch_va);
2330 			return false;
2331 		}
2332 
2333 		/*
2334 		 * The scratch area is outside the GHCB. The operation will
2335 		 * dictate whether the buffer needs to be synced before running
2336 		 * the vCPU next time (i.e. a read was requested so the data
2337 		 * must be written back to the guest memory).
2338 		 */
2339 		svm->ghcb_sa_sync = sync;
2340 		svm->ghcb_sa_free = true;
2341 	}
2342 
2343 	svm->ghcb_sa = scratch_va;
2344 	svm->ghcb_sa_len = len;
2345 
2346 	return true;
2347 }
2348 
2349 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
2350 			      unsigned int pos)
2351 {
2352 	svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
2353 	svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
2354 }
2355 
2356 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
2357 {
2358 	return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
2359 }
2360 
2361 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
2362 {
2363 	svm->vmcb->control.ghcb_gpa = value;
2364 }
2365 
2366 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
2367 {
2368 	struct vmcb_control_area *control = &svm->vmcb->control;
2369 	struct kvm_vcpu *vcpu = &svm->vcpu;
2370 	u64 ghcb_info;
2371 	int ret = 1;
2372 
2373 	ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
2374 
2375 	trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
2376 					     control->ghcb_gpa);
2377 
2378 	switch (ghcb_info) {
2379 	case GHCB_MSR_SEV_INFO_REQ:
2380 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
2381 						    GHCB_VERSION_MIN,
2382 						    sev_enc_bit));
2383 		break;
2384 	case GHCB_MSR_CPUID_REQ: {
2385 		u64 cpuid_fn, cpuid_reg, cpuid_value;
2386 
2387 		cpuid_fn = get_ghcb_msr_bits(svm,
2388 					     GHCB_MSR_CPUID_FUNC_MASK,
2389 					     GHCB_MSR_CPUID_FUNC_POS);
2390 
2391 		/* Initialize the registers needed by the CPUID intercept */
2392 		vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
2393 		vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2394 
2395 		ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
2396 		if (!ret) {
2397 			ret = -EINVAL;
2398 			break;
2399 		}
2400 
2401 		cpuid_reg = get_ghcb_msr_bits(svm,
2402 					      GHCB_MSR_CPUID_REG_MASK,
2403 					      GHCB_MSR_CPUID_REG_POS);
2404 		if (cpuid_reg == 0)
2405 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
2406 		else if (cpuid_reg == 1)
2407 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
2408 		else if (cpuid_reg == 2)
2409 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
2410 		else
2411 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
2412 
2413 		set_ghcb_msr_bits(svm, cpuid_value,
2414 				  GHCB_MSR_CPUID_VALUE_MASK,
2415 				  GHCB_MSR_CPUID_VALUE_POS);
2416 
2417 		set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
2418 				  GHCB_MSR_INFO_MASK,
2419 				  GHCB_MSR_INFO_POS);
2420 		break;
2421 	}
2422 	case GHCB_MSR_TERM_REQ: {
2423 		u64 reason_set, reason_code;
2424 
2425 		reason_set = get_ghcb_msr_bits(svm,
2426 					       GHCB_MSR_TERM_REASON_SET_MASK,
2427 					       GHCB_MSR_TERM_REASON_SET_POS);
2428 		reason_code = get_ghcb_msr_bits(svm,
2429 						GHCB_MSR_TERM_REASON_MASK,
2430 						GHCB_MSR_TERM_REASON_POS);
2431 		pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
2432 			reason_set, reason_code);
2433 		fallthrough;
2434 	}
2435 	default:
2436 		ret = -EINVAL;
2437 	}
2438 
2439 	trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
2440 					    control->ghcb_gpa, ret);
2441 
2442 	return ret;
2443 }
2444 
2445 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
2446 {
2447 	struct vcpu_svm *svm = to_svm(vcpu);
2448 	struct vmcb_control_area *control = &svm->vmcb->control;
2449 	u64 ghcb_gpa, exit_code;
2450 	struct ghcb *ghcb;
2451 	int ret;
2452 
2453 	/* Validate the GHCB */
2454 	ghcb_gpa = control->ghcb_gpa;
2455 	if (ghcb_gpa & GHCB_MSR_INFO_MASK)
2456 		return sev_handle_vmgexit_msr_protocol(svm);
2457 
2458 	if (!ghcb_gpa) {
2459 		vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n");
2460 		return -EINVAL;
2461 	}
2462 
2463 	if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->ghcb_map)) {
2464 		/* Unable to map GHCB from guest */
2465 		vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
2466 			    ghcb_gpa);
2467 		return -EINVAL;
2468 	}
2469 
2470 	svm->ghcb = svm->ghcb_map.hva;
2471 	ghcb = svm->ghcb_map.hva;
2472 
2473 	trace_kvm_vmgexit_enter(vcpu->vcpu_id, ghcb);
2474 
2475 	exit_code = ghcb_get_sw_exit_code(ghcb);
2476 
2477 	ret = sev_es_validate_vmgexit(svm);
2478 	if (ret)
2479 		return ret;
2480 
2481 	sev_es_sync_from_ghcb(svm);
2482 	ghcb_set_sw_exit_info_1(ghcb, 0);
2483 	ghcb_set_sw_exit_info_2(ghcb, 0);
2484 
2485 	ret = -EINVAL;
2486 	switch (exit_code) {
2487 	case SVM_VMGEXIT_MMIO_READ:
2488 		if (!setup_vmgexit_scratch(svm, true, control->exit_info_2))
2489 			break;
2490 
2491 		ret = kvm_sev_es_mmio_read(vcpu,
2492 					   control->exit_info_1,
2493 					   control->exit_info_2,
2494 					   svm->ghcb_sa);
2495 		break;
2496 	case SVM_VMGEXIT_MMIO_WRITE:
2497 		if (!setup_vmgexit_scratch(svm, false, control->exit_info_2))
2498 			break;
2499 
2500 		ret = kvm_sev_es_mmio_write(vcpu,
2501 					    control->exit_info_1,
2502 					    control->exit_info_2,
2503 					    svm->ghcb_sa);
2504 		break;
2505 	case SVM_VMGEXIT_NMI_COMPLETE:
2506 		ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_IRET);
2507 		break;
2508 	case SVM_VMGEXIT_AP_HLT_LOOP:
2509 		ret = kvm_emulate_ap_reset_hold(vcpu);
2510 		break;
2511 	case SVM_VMGEXIT_AP_JUMP_TABLE: {
2512 		struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
2513 
2514 		switch (control->exit_info_1) {
2515 		case 0:
2516 			/* Set AP jump table address */
2517 			sev->ap_jump_table = control->exit_info_2;
2518 			break;
2519 		case 1:
2520 			/* Get AP jump table address */
2521 			ghcb_set_sw_exit_info_2(ghcb, sev->ap_jump_table);
2522 			break;
2523 		default:
2524 			pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
2525 			       control->exit_info_1);
2526 			ghcb_set_sw_exit_info_1(ghcb, 1);
2527 			ghcb_set_sw_exit_info_2(ghcb,
2528 						X86_TRAP_UD |
2529 						SVM_EVTINJ_TYPE_EXEPT |
2530 						SVM_EVTINJ_VALID);
2531 		}
2532 
2533 		ret = 1;
2534 		break;
2535 	}
2536 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
2537 		vcpu_unimpl(vcpu,
2538 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
2539 			    control->exit_info_1, control->exit_info_2);
2540 		break;
2541 	default:
2542 		ret = svm_invoke_exit_handler(vcpu, exit_code);
2543 	}
2544 
2545 	return ret;
2546 }
2547 
2548 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
2549 {
2550 	if (!setup_vmgexit_scratch(svm, in, svm->vmcb->control.exit_info_2))
2551 		return -EINVAL;
2552 
2553 	return kvm_sev_es_string_io(&svm->vcpu, size, port,
2554 				    svm->ghcb_sa, svm->ghcb_sa_len, in);
2555 }
2556 
2557 void sev_es_init_vmcb(struct vcpu_svm *svm)
2558 {
2559 	struct kvm_vcpu *vcpu = &svm->vcpu;
2560 
2561 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE;
2562 	svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
2563 
2564 	/*
2565 	 * An SEV-ES guest requires a VMSA area that is a separate from the
2566 	 * VMCB page. Do not include the encryption mask on the VMSA physical
2567 	 * address since hardware will access it using the guest key.
2568 	 */
2569 	svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);
2570 
2571 	/* Can't intercept CR register access, HV can't modify CR registers */
2572 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
2573 	svm_clr_intercept(svm, INTERCEPT_CR4_READ);
2574 	svm_clr_intercept(svm, INTERCEPT_CR8_READ);
2575 	svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
2576 	svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
2577 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
2578 
2579 	svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
2580 
2581 	/* Track EFER/CR register changes */
2582 	svm_set_intercept(svm, TRAP_EFER_WRITE);
2583 	svm_set_intercept(svm, TRAP_CR0_WRITE);
2584 	svm_set_intercept(svm, TRAP_CR4_WRITE);
2585 	svm_set_intercept(svm, TRAP_CR8_WRITE);
2586 
2587 	/* No support for enable_vmware_backdoor */
2588 	clr_exception_intercept(svm, GP_VECTOR);
2589 
2590 	/* Can't intercept XSETBV, HV can't modify XCR0 directly */
2591 	svm_clr_intercept(svm, INTERCEPT_XSETBV);
2592 
2593 	/* Clear intercepts on selected MSRs */
2594 	set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1);
2595 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1);
2596 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
2597 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
2598 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
2599 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
2600 }
2601 
2602 void sev_es_create_vcpu(struct vcpu_svm *svm)
2603 {
2604 	/*
2605 	 * Set the GHCB MSR value as per the GHCB specification when creating
2606 	 * a vCPU for an SEV-ES guest.
2607 	 */
2608 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
2609 					    GHCB_VERSION_MIN,
2610 					    sev_enc_bit));
2611 }
2612 
2613 void sev_es_prepare_guest_switch(struct vcpu_svm *svm, unsigned int cpu)
2614 {
2615 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2616 	struct vmcb_save_area *hostsa;
2617 
2618 	/*
2619 	 * As an SEV-ES guest, hardware will restore the host state on VMEXIT,
2620 	 * of which one step is to perform a VMLOAD. Since hardware does not
2621 	 * perform a VMSAVE on VMRUN, the host savearea must be updated.
2622 	 */
2623 	vmsave(__sme_page_pa(sd->save_area));
2624 
2625 	/* XCR0 is restored on VMEXIT, save the current host value */
2626 	hostsa = (struct vmcb_save_area *)(page_address(sd->save_area) + 0x400);
2627 	hostsa->xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
2628 
2629 	/* PKRU is restored on VMEXIT, save the current host value */
2630 	hostsa->pkru = read_pkru();
2631 
2632 	/* MSR_IA32_XSS is restored on VMEXIT, save the currnet host value */
2633 	hostsa->xss = host_xss;
2634 }
2635 
2636 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
2637 {
2638 	struct vcpu_svm *svm = to_svm(vcpu);
2639 
2640 	/* First SIPI: Use the values as initially set by the VMM */
2641 	if (!svm->received_first_sipi) {
2642 		svm->received_first_sipi = true;
2643 		return;
2644 	}
2645 
2646 	/*
2647 	 * Subsequent SIPI: Return from an AP Reset Hold VMGEXIT, where
2648 	 * the guest will set the CS and RIP. Set SW_EXIT_INFO_2 to a
2649 	 * non-zero value.
2650 	 */
2651 	if (!svm->ghcb)
2652 		return;
2653 
2654 	ghcb_set_sw_exit_info_2(svm->ghcb, 1);
2655 }
2656