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