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