xref: /openbmc/linux/arch/x86/kvm/svm/sev.c (revision 6548d543)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM-SEV support
6  *
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/kvm_types.h>
12 #include <linux/kvm_host.h>
13 #include <linux/kernel.h>
14 #include <linux/highmem.h>
15 #include <linux/psp.h>
16 #include <linux/psp-sev.h>
17 #include <linux/pagemap.h>
18 #include <linux/swap.h>
19 #include <linux/misc_cgroup.h>
20 #include <linux/processor.h>
21 #include <linux/trace_events.h>
22 
23 #include <asm/pkru.h>
24 #include <asm/trapnr.h>
25 #include <asm/fpu/xcr.h>
26 #include <asm/debugreg.h>
27 
28 #include "mmu.h"
29 #include "x86.h"
30 #include "svm.h"
31 #include "svm_ops.h"
32 #include "cpuid.h"
33 #include "trace.h"
34 
35 #ifndef CONFIG_KVM_AMD_SEV
36 /*
37  * When this config is not defined, SEV feature is not supported and APIs in
38  * this file are not used but this file still gets compiled into the KVM AMD
39  * module.
40  *
41  * We will not have MISC_CG_RES_SEV and MISC_CG_RES_SEV_ES entries in the enum
42  * misc_res_type {} defined in linux/misc_cgroup.h.
43  *
44  * Below macros allow compilation to succeed.
45  */
46 #define MISC_CG_RES_SEV MISC_CG_RES_TYPES
47 #define MISC_CG_RES_SEV_ES MISC_CG_RES_TYPES
48 #endif
49 
50 #ifdef CONFIG_KVM_AMD_SEV
51 /* enable/disable SEV support */
52 static bool sev_enabled = true;
53 module_param_named(sev, sev_enabled, bool, 0444);
54 
55 /* enable/disable SEV-ES support */
56 static bool sev_es_enabled = true;
57 module_param_named(sev_es, sev_es_enabled, bool, 0444);
58 
59 /* enable/disable SEV-ES DebugSwap support */
60 static bool sev_es_debug_swap_enabled = false;
61 module_param_named(debug_swap, sev_es_debug_swap_enabled, bool, 0444);
62 #else
63 #define sev_enabled false
64 #define sev_es_enabled false
65 #define sev_es_debug_swap_enabled false
66 #endif /* CONFIG_KVM_AMD_SEV */
67 
68 static u8 sev_enc_bit;
69 static DECLARE_RWSEM(sev_deactivate_lock);
70 static DEFINE_MUTEX(sev_bitmap_lock);
71 unsigned int max_sev_asid;
72 static unsigned int min_sev_asid;
73 static unsigned long sev_me_mask;
74 static unsigned int nr_asids;
75 static unsigned long *sev_asid_bitmap;
76 static unsigned long *sev_reclaim_asid_bitmap;
77 
78 struct enc_region {
79 	struct list_head list;
80 	unsigned long npages;
81 	struct page **pages;
82 	unsigned long uaddr;
83 	unsigned long size;
84 };
85 
86 /* Called with the sev_bitmap_lock held, or on shutdown  */
87 static int sev_flush_asids(unsigned int min_asid, unsigned int max_asid)
88 {
89 	int ret, error = 0;
90 	unsigned int asid;
91 
92 	/* Check if there are any ASIDs to reclaim before performing a flush */
93 	asid = find_next_bit(sev_reclaim_asid_bitmap, nr_asids, min_asid);
94 	if (asid > max_asid)
95 		return -EBUSY;
96 
97 	/*
98 	 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
99 	 * so it must be guarded.
100 	 */
101 	down_write(&sev_deactivate_lock);
102 
103 	wbinvd_on_all_cpus();
104 	ret = sev_guest_df_flush(&error);
105 
106 	up_write(&sev_deactivate_lock);
107 
108 	if (ret)
109 		pr_err("SEV: DF_FLUSH failed, ret=%d, error=%#x\n", ret, error);
110 
111 	return ret;
112 }
113 
114 static inline bool is_mirroring_enc_context(struct kvm *kvm)
115 {
116 	return !!to_kvm_svm(kvm)->sev_info.enc_context_owner;
117 }
118 
119 /* Must be called with the sev_bitmap_lock held */
120 static bool __sev_recycle_asids(unsigned int min_asid, unsigned int max_asid)
121 {
122 	if (sev_flush_asids(min_asid, max_asid))
123 		return false;
124 
125 	/* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */
126 	bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
127 		   nr_asids);
128 	bitmap_zero(sev_reclaim_asid_bitmap, nr_asids);
129 
130 	return true;
131 }
132 
133 static int sev_misc_cg_try_charge(struct kvm_sev_info *sev)
134 {
135 	enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
136 	return misc_cg_try_charge(type, sev->misc_cg, 1);
137 }
138 
139 static void sev_misc_cg_uncharge(struct kvm_sev_info *sev)
140 {
141 	enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
142 	misc_cg_uncharge(type, sev->misc_cg, 1);
143 }
144 
145 static int sev_asid_new(struct kvm_sev_info *sev)
146 {
147 	/*
148 	 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid.
149 	 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1.
150 	 * Note: min ASID can end up larger than the max if basic SEV support is
151 	 * effectively disabled by disallowing use of ASIDs for SEV guests.
152 	 */
153 	unsigned int min_asid = sev->es_active ? 1 : min_sev_asid;
154 	unsigned int max_asid = sev->es_active ? min_sev_asid - 1 : max_sev_asid;
155 	unsigned int asid;
156 	bool retry = true;
157 	int ret;
158 
159 	if (min_asid > max_asid)
160 		return -ENOTTY;
161 
162 	WARN_ON(sev->misc_cg);
163 	sev->misc_cg = get_current_misc_cg();
164 	ret = sev_misc_cg_try_charge(sev);
165 	if (ret) {
166 		put_misc_cg(sev->misc_cg);
167 		sev->misc_cg = NULL;
168 		return ret;
169 	}
170 
171 	mutex_lock(&sev_bitmap_lock);
172 
173 again:
174 	asid = find_next_zero_bit(sev_asid_bitmap, max_asid + 1, min_asid);
175 	if (asid > max_asid) {
176 		if (retry && __sev_recycle_asids(min_asid, max_asid)) {
177 			retry = false;
178 			goto again;
179 		}
180 		mutex_unlock(&sev_bitmap_lock);
181 		ret = -EBUSY;
182 		goto e_uncharge;
183 	}
184 
185 	__set_bit(asid, sev_asid_bitmap);
186 
187 	mutex_unlock(&sev_bitmap_lock);
188 
189 	return asid;
190 e_uncharge:
191 	sev_misc_cg_uncharge(sev);
192 	put_misc_cg(sev->misc_cg);
193 	sev->misc_cg = NULL;
194 	return ret;
195 }
196 
197 static unsigned int sev_get_asid(struct kvm *kvm)
198 {
199 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
200 
201 	return sev->asid;
202 }
203 
204 static void sev_asid_free(struct kvm_sev_info *sev)
205 {
206 	struct svm_cpu_data *sd;
207 	int cpu;
208 
209 	mutex_lock(&sev_bitmap_lock);
210 
211 	__set_bit(sev->asid, sev_reclaim_asid_bitmap);
212 
213 	for_each_possible_cpu(cpu) {
214 		sd = per_cpu_ptr(&svm_data, cpu);
215 		sd->sev_vmcbs[sev->asid] = NULL;
216 	}
217 
218 	mutex_unlock(&sev_bitmap_lock);
219 
220 	sev_misc_cg_uncharge(sev);
221 	put_misc_cg(sev->misc_cg);
222 	sev->misc_cg = NULL;
223 }
224 
225 static void sev_decommission(unsigned int handle)
226 {
227 	struct sev_data_decommission decommission;
228 
229 	if (!handle)
230 		return;
231 
232 	decommission.handle = handle;
233 	sev_guest_decommission(&decommission, NULL);
234 }
235 
236 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
237 {
238 	struct sev_data_deactivate deactivate;
239 
240 	if (!handle)
241 		return;
242 
243 	deactivate.handle = handle;
244 
245 	/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
246 	down_read(&sev_deactivate_lock);
247 	sev_guest_deactivate(&deactivate, NULL);
248 	up_read(&sev_deactivate_lock);
249 
250 	sev_decommission(handle);
251 }
252 
253 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
254 {
255 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
256 	int asid, ret;
257 
258 	if (kvm->created_vcpus)
259 		return -EINVAL;
260 
261 	ret = -EBUSY;
262 	if (unlikely(sev->active))
263 		return ret;
264 
265 	sev->active = true;
266 	sev->es_active = argp->id == KVM_SEV_ES_INIT;
267 	asid = sev_asid_new(sev);
268 	if (asid < 0)
269 		goto e_no_asid;
270 	sev->asid = asid;
271 
272 	ret = sev_platform_init(&argp->error);
273 	if (ret)
274 		goto e_free;
275 
276 	INIT_LIST_HEAD(&sev->regions_list);
277 	INIT_LIST_HEAD(&sev->mirror_vms);
278 
279 	kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_SEV);
280 
281 	return 0;
282 
283 e_free:
284 	sev_asid_free(sev);
285 	sev->asid = 0;
286 e_no_asid:
287 	sev->es_active = false;
288 	sev->active = false;
289 	return ret;
290 }
291 
292 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
293 {
294 	unsigned int asid = sev_get_asid(kvm);
295 	struct sev_data_activate activate;
296 	int ret;
297 
298 	/* activate ASID on the given handle */
299 	activate.handle = handle;
300 	activate.asid   = asid;
301 	ret = sev_guest_activate(&activate, error);
302 
303 	return ret;
304 }
305 
306 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
307 {
308 	struct fd f;
309 	int ret;
310 
311 	f = fdget(fd);
312 	if (!f.file)
313 		return -EBADF;
314 
315 	ret = sev_issue_cmd_external_user(f.file, id, data, error);
316 
317 	fdput(f);
318 	return ret;
319 }
320 
321 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
322 {
323 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
324 
325 	return __sev_issue_cmd(sev->fd, id, data, error);
326 }
327 
328 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
329 {
330 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
331 	struct sev_data_launch_start start;
332 	struct kvm_sev_launch_start params;
333 	void *dh_blob, *session_blob;
334 	int *error = &argp->error;
335 	int ret;
336 
337 	if (!sev_guest(kvm))
338 		return -ENOTTY;
339 
340 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
341 		return -EFAULT;
342 
343 	memset(&start, 0, sizeof(start));
344 
345 	dh_blob = NULL;
346 	if (params.dh_uaddr) {
347 		dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
348 		if (IS_ERR(dh_blob))
349 			return PTR_ERR(dh_blob);
350 
351 		start.dh_cert_address = __sme_set(__pa(dh_blob));
352 		start.dh_cert_len = params.dh_len;
353 	}
354 
355 	session_blob = NULL;
356 	if (params.session_uaddr) {
357 		session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
358 		if (IS_ERR(session_blob)) {
359 			ret = PTR_ERR(session_blob);
360 			goto e_free_dh;
361 		}
362 
363 		start.session_address = __sme_set(__pa(session_blob));
364 		start.session_len = params.session_len;
365 	}
366 
367 	start.handle = params.handle;
368 	start.policy = params.policy;
369 
370 	/* create memory encryption context */
371 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, &start, error);
372 	if (ret)
373 		goto e_free_session;
374 
375 	/* Bind ASID to this guest */
376 	ret = sev_bind_asid(kvm, start.handle, error);
377 	if (ret) {
378 		sev_decommission(start.handle);
379 		goto e_free_session;
380 	}
381 
382 	/* return handle to userspace */
383 	params.handle = start.handle;
384 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params))) {
385 		sev_unbind_asid(kvm, start.handle);
386 		ret = -EFAULT;
387 		goto e_free_session;
388 	}
389 
390 	sev->handle = start.handle;
391 	sev->fd = argp->sev_fd;
392 
393 e_free_session:
394 	kfree(session_blob);
395 e_free_dh:
396 	kfree(dh_blob);
397 	return ret;
398 }
399 
400 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
401 				    unsigned long ulen, unsigned long *n,
402 				    int write)
403 {
404 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
405 	unsigned long npages, size;
406 	int npinned;
407 	unsigned long locked, lock_limit;
408 	struct page **pages;
409 	unsigned long first, last;
410 	int ret;
411 
412 	lockdep_assert_held(&kvm->lock);
413 
414 	if (ulen == 0 || uaddr + ulen < uaddr)
415 		return ERR_PTR(-EINVAL);
416 
417 	/* Calculate number of pages. */
418 	first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
419 	last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
420 	npages = (last - first + 1);
421 
422 	locked = sev->pages_locked + npages;
423 	lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
424 	if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
425 		pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
426 		return ERR_PTR(-ENOMEM);
427 	}
428 
429 	if (WARN_ON_ONCE(npages > INT_MAX))
430 		return ERR_PTR(-EINVAL);
431 
432 	/* Avoid using vmalloc for smaller buffers. */
433 	size = npages * sizeof(struct page *);
434 	if (size > PAGE_SIZE)
435 		pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
436 	else
437 		pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
438 
439 	if (!pages)
440 		return ERR_PTR(-ENOMEM);
441 
442 	/* Pin the user virtual address. */
443 	npinned = pin_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
444 	if (npinned != npages) {
445 		pr_err("SEV: Failure locking %lu pages.\n", npages);
446 		ret = -ENOMEM;
447 		goto err;
448 	}
449 
450 	*n = npages;
451 	sev->pages_locked = locked;
452 
453 	return pages;
454 
455 err:
456 	if (npinned > 0)
457 		unpin_user_pages(pages, npinned);
458 
459 	kvfree(pages);
460 	return ERR_PTR(ret);
461 }
462 
463 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
464 			     unsigned long npages)
465 {
466 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
467 
468 	unpin_user_pages(pages, npages);
469 	kvfree(pages);
470 	sev->pages_locked -= npages;
471 }
472 
473 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
474 {
475 	uint8_t *page_virtual;
476 	unsigned long i;
477 
478 	if (this_cpu_has(X86_FEATURE_SME_COHERENT) || npages == 0 ||
479 	    pages == NULL)
480 		return;
481 
482 	for (i = 0; i < npages; i++) {
483 		page_virtual = kmap_local_page(pages[i]);
484 		clflush_cache_range(page_virtual, PAGE_SIZE);
485 		kunmap_local(page_virtual);
486 		cond_resched();
487 	}
488 }
489 
490 static unsigned long get_num_contig_pages(unsigned long idx,
491 				struct page **inpages, unsigned long npages)
492 {
493 	unsigned long paddr, next_paddr;
494 	unsigned long i = idx + 1, pages = 1;
495 
496 	/* find the number of contiguous pages starting from idx */
497 	paddr = __sme_page_pa(inpages[idx]);
498 	while (i < npages) {
499 		next_paddr = __sme_page_pa(inpages[i++]);
500 		if ((paddr + PAGE_SIZE) == next_paddr) {
501 			pages++;
502 			paddr = next_paddr;
503 			continue;
504 		}
505 		break;
506 	}
507 
508 	return pages;
509 }
510 
511 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
512 {
513 	unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
514 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
515 	struct kvm_sev_launch_update_data params;
516 	struct sev_data_launch_update_data data;
517 	struct page **inpages;
518 	int ret;
519 
520 	if (!sev_guest(kvm))
521 		return -ENOTTY;
522 
523 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
524 		return -EFAULT;
525 
526 	vaddr = params.uaddr;
527 	size = params.len;
528 	vaddr_end = vaddr + size;
529 
530 	/* Lock the user memory. */
531 	inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
532 	if (IS_ERR(inpages))
533 		return PTR_ERR(inpages);
534 
535 	/*
536 	 * Flush (on non-coherent CPUs) before LAUNCH_UPDATE encrypts pages in
537 	 * place; the cache may contain the data that was written unencrypted.
538 	 */
539 	sev_clflush_pages(inpages, npages);
540 
541 	data.reserved = 0;
542 	data.handle = sev->handle;
543 
544 	for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
545 		int offset, len;
546 
547 		/*
548 		 * If the user buffer is not page-aligned, calculate the offset
549 		 * within the page.
550 		 */
551 		offset = vaddr & (PAGE_SIZE - 1);
552 
553 		/* Calculate the number of pages that can be encrypted in one go. */
554 		pages = get_num_contig_pages(i, inpages, npages);
555 
556 		len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
557 
558 		data.len = len;
559 		data.address = __sme_page_pa(inpages[i]) + offset;
560 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, &data, &argp->error);
561 		if (ret)
562 			goto e_unpin;
563 
564 		size -= len;
565 		next_vaddr = vaddr + len;
566 	}
567 
568 e_unpin:
569 	/* content of memory is updated, mark pages dirty */
570 	for (i = 0; i < npages; i++) {
571 		set_page_dirty_lock(inpages[i]);
572 		mark_page_accessed(inpages[i]);
573 	}
574 	/* unlock the user pages */
575 	sev_unpin_memory(kvm, inpages, npages);
576 	return ret;
577 }
578 
579 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
580 {
581 	struct sev_es_save_area *save = svm->sev_es.vmsa;
582 
583 	/* Check some debug related fields before encrypting the VMSA */
584 	if (svm->vcpu.guest_debug || (svm->vmcb->save.dr7 & ~DR7_FIXED_1))
585 		return -EINVAL;
586 
587 	/*
588 	 * SEV-ES will use a VMSA that is pointed to by the VMCB, not
589 	 * the traditional VMSA that is part of the VMCB. Copy the
590 	 * traditional VMSA as it has been built so far (in prep
591 	 * for LAUNCH_UPDATE_VMSA) to be the initial SEV-ES state.
592 	 */
593 	memcpy(save, &svm->vmcb->save, sizeof(svm->vmcb->save));
594 
595 	/* Sync registgers */
596 	save->rax = svm->vcpu.arch.regs[VCPU_REGS_RAX];
597 	save->rbx = svm->vcpu.arch.regs[VCPU_REGS_RBX];
598 	save->rcx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
599 	save->rdx = svm->vcpu.arch.regs[VCPU_REGS_RDX];
600 	save->rsp = svm->vcpu.arch.regs[VCPU_REGS_RSP];
601 	save->rbp = svm->vcpu.arch.regs[VCPU_REGS_RBP];
602 	save->rsi = svm->vcpu.arch.regs[VCPU_REGS_RSI];
603 	save->rdi = svm->vcpu.arch.regs[VCPU_REGS_RDI];
604 #ifdef CONFIG_X86_64
605 	save->r8  = svm->vcpu.arch.regs[VCPU_REGS_R8];
606 	save->r9  = svm->vcpu.arch.regs[VCPU_REGS_R9];
607 	save->r10 = svm->vcpu.arch.regs[VCPU_REGS_R10];
608 	save->r11 = svm->vcpu.arch.regs[VCPU_REGS_R11];
609 	save->r12 = svm->vcpu.arch.regs[VCPU_REGS_R12];
610 	save->r13 = svm->vcpu.arch.regs[VCPU_REGS_R13];
611 	save->r14 = svm->vcpu.arch.regs[VCPU_REGS_R14];
612 	save->r15 = svm->vcpu.arch.regs[VCPU_REGS_R15];
613 #endif
614 	save->rip = svm->vcpu.arch.regs[VCPU_REGS_RIP];
615 
616 	/* Sync some non-GPR registers before encrypting */
617 	save->xcr0 = svm->vcpu.arch.xcr0;
618 	save->pkru = svm->vcpu.arch.pkru;
619 	save->xss  = svm->vcpu.arch.ia32_xss;
620 	save->dr6  = svm->vcpu.arch.dr6;
621 
622 	if (sev_es_debug_swap_enabled) {
623 		save->sev_features |= SVM_SEV_FEAT_DEBUG_SWAP;
624 		pr_warn_once("Enabling DebugSwap with KVM_SEV_ES_INIT. "
625 			     "This will not work starting with Linux 6.10\n");
626 	}
627 
628 	pr_debug("Virtual Machine Save Area (VMSA):\n");
629 	print_hex_dump_debug("", DUMP_PREFIX_NONE, 16, 1, save, sizeof(*save), false);
630 
631 	return 0;
632 }
633 
634 static int __sev_launch_update_vmsa(struct kvm *kvm, struct kvm_vcpu *vcpu,
635 				    int *error)
636 {
637 	struct sev_data_launch_update_vmsa vmsa;
638 	struct vcpu_svm *svm = to_svm(vcpu);
639 	int ret;
640 
641 	if (vcpu->guest_debug) {
642 		pr_warn_once("KVM_SET_GUEST_DEBUG for SEV-ES guest is not supported");
643 		return -EINVAL;
644 	}
645 
646 	/* Perform some pre-encryption checks against the VMSA */
647 	ret = sev_es_sync_vmsa(svm);
648 	if (ret)
649 		return ret;
650 
651 	/*
652 	 * The LAUNCH_UPDATE_VMSA command will perform in-place encryption of
653 	 * the VMSA memory content (i.e it will write the same memory region
654 	 * with the guest's key), so invalidate it first.
655 	 */
656 	clflush_cache_range(svm->sev_es.vmsa, PAGE_SIZE);
657 
658 	vmsa.reserved = 0;
659 	vmsa.handle = to_kvm_svm(kvm)->sev_info.handle;
660 	vmsa.address = __sme_pa(svm->sev_es.vmsa);
661 	vmsa.len = PAGE_SIZE;
662 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_VMSA, &vmsa, error);
663 	if (ret)
664 	  return ret;
665 
666 	vcpu->arch.guest_state_protected = true;
667 
668 	/*
669 	 * SEV-ES guest mandates LBR Virtualization to be _always_ ON. Enable it
670 	 * only after setting guest_state_protected because KVM_SET_MSRS allows
671 	 * dynamic toggling of LBRV (for performance reason) on write access to
672 	 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set.
673 	 */
674 	svm_enable_lbrv(vcpu);
675 	return 0;
676 }
677 
678 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
679 {
680 	struct kvm_vcpu *vcpu;
681 	unsigned long i;
682 	int ret;
683 
684 	if (!sev_es_guest(kvm))
685 		return -ENOTTY;
686 
687 	kvm_for_each_vcpu(i, vcpu, kvm) {
688 		ret = mutex_lock_killable(&vcpu->mutex);
689 		if (ret)
690 			return ret;
691 
692 		ret = __sev_launch_update_vmsa(kvm, vcpu, &argp->error);
693 
694 		mutex_unlock(&vcpu->mutex);
695 		if (ret)
696 			return ret;
697 	}
698 
699 	return 0;
700 }
701 
702 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
703 {
704 	void __user *measure = (void __user *)(uintptr_t)argp->data;
705 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
706 	struct sev_data_launch_measure data;
707 	struct kvm_sev_launch_measure params;
708 	void __user *p = NULL;
709 	void *blob = NULL;
710 	int ret;
711 
712 	if (!sev_guest(kvm))
713 		return -ENOTTY;
714 
715 	if (copy_from_user(&params, measure, sizeof(params)))
716 		return -EFAULT;
717 
718 	memset(&data, 0, sizeof(data));
719 
720 	/* User wants to query the blob length */
721 	if (!params.len)
722 		goto cmd;
723 
724 	p = (void __user *)(uintptr_t)params.uaddr;
725 	if (p) {
726 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
727 			return -EINVAL;
728 
729 		blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
730 		if (!blob)
731 			return -ENOMEM;
732 
733 		data.address = __psp_pa(blob);
734 		data.len = params.len;
735 	}
736 
737 cmd:
738 	data.handle = sev->handle;
739 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, &data, &argp->error);
740 
741 	/*
742 	 * If we query the session length, FW responded with expected data.
743 	 */
744 	if (!params.len)
745 		goto done;
746 
747 	if (ret)
748 		goto e_free_blob;
749 
750 	if (blob) {
751 		if (copy_to_user(p, blob, params.len))
752 			ret = -EFAULT;
753 	}
754 
755 done:
756 	params.len = data.len;
757 	if (copy_to_user(measure, &params, sizeof(params)))
758 		ret = -EFAULT;
759 e_free_blob:
760 	kfree(blob);
761 	return ret;
762 }
763 
764 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
765 {
766 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
767 	struct sev_data_launch_finish data;
768 
769 	if (!sev_guest(kvm))
770 		return -ENOTTY;
771 
772 	data.handle = sev->handle;
773 	return sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, &data, &argp->error);
774 }
775 
776 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
777 {
778 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
779 	struct kvm_sev_guest_status params;
780 	struct sev_data_guest_status data;
781 	int ret;
782 
783 	if (!sev_guest(kvm))
784 		return -ENOTTY;
785 
786 	memset(&data, 0, sizeof(data));
787 
788 	data.handle = sev->handle;
789 	ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, &data, &argp->error);
790 	if (ret)
791 		return ret;
792 
793 	params.policy = data.policy;
794 	params.state = data.state;
795 	params.handle = data.handle;
796 
797 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
798 		ret = -EFAULT;
799 
800 	return ret;
801 }
802 
803 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
804 			       unsigned long dst, int size,
805 			       int *error, bool enc)
806 {
807 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
808 	struct sev_data_dbg data;
809 
810 	data.reserved = 0;
811 	data.handle = sev->handle;
812 	data.dst_addr = dst;
813 	data.src_addr = src;
814 	data.len = size;
815 
816 	return sev_issue_cmd(kvm,
817 			     enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
818 			     &data, error);
819 }
820 
821 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
822 			     unsigned long dst_paddr, int sz, int *err)
823 {
824 	int offset;
825 
826 	/*
827 	 * Its safe to read more than we are asked, caller should ensure that
828 	 * destination has enough space.
829 	 */
830 	offset = src_paddr & 15;
831 	src_paddr = round_down(src_paddr, 16);
832 	sz = round_up(sz + offset, 16);
833 
834 	return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
835 }
836 
837 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
838 				  void __user *dst_uaddr,
839 				  unsigned long dst_paddr,
840 				  int size, int *err)
841 {
842 	struct page *tpage = NULL;
843 	int ret, offset;
844 
845 	/* if inputs are not 16-byte then use intermediate buffer */
846 	if (!IS_ALIGNED(dst_paddr, 16) ||
847 	    !IS_ALIGNED(paddr,     16) ||
848 	    !IS_ALIGNED(size,      16)) {
849 		tpage = (void *)alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
850 		if (!tpage)
851 			return -ENOMEM;
852 
853 		dst_paddr = __sme_page_pa(tpage);
854 	}
855 
856 	ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
857 	if (ret)
858 		goto e_free;
859 
860 	if (tpage) {
861 		offset = paddr & 15;
862 		if (copy_to_user(dst_uaddr, page_address(tpage) + offset, size))
863 			ret = -EFAULT;
864 	}
865 
866 e_free:
867 	if (tpage)
868 		__free_page(tpage);
869 
870 	return ret;
871 }
872 
873 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
874 				  void __user *vaddr,
875 				  unsigned long dst_paddr,
876 				  void __user *dst_vaddr,
877 				  int size, int *error)
878 {
879 	struct page *src_tpage = NULL;
880 	struct page *dst_tpage = NULL;
881 	int ret, len = size;
882 
883 	/* If source buffer is not aligned then use an intermediate buffer */
884 	if (!IS_ALIGNED((unsigned long)vaddr, 16)) {
885 		src_tpage = alloc_page(GFP_KERNEL_ACCOUNT);
886 		if (!src_tpage)
887 			return -ENOMEM;
888 
889 		if (copy_from_user(page_address(src_tpage), vaddr, size)) {
890 			__free_page(src_tpage);
891 			return -EFAULT;
892 		}
893 
894 		paddr = __sme_page_pa(src_tpage);
895 	}
896 
897 	/*
898 	 *  If destination buffer or length is not aligned then do read-modify-write:
899 	 *   - decrypt destination in an intermediate buffer
900 	 *   - copy the source buffer in an intermediate buffer
901 	 *   - use the intermediate buffer as source buffer
902 	 */
903 	if (!IS_ALIGNED((unsigned long)dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
904 		int dst_offset;
905 
906 		dst_tpage = alloc_page(GFP_KERNEL_ACCOUNT);
907 		if (!dst_tpage) {
908 			ret = -ENOMEM;
909 			goto e_free;
910 		}
911 
912 		ret = __sev_dbg_decrypt(kvm, dst_paddr,
913 					__sme_page_pa(dst_tpage), size, error);
914 		if (ret)
915 			goto e_free;
916 
917 		/*
918 		 *  If source is kernel buffer then use memcpy() otherwise
919 		 *  copy_from_user().
920 		 */
921 		dst_offset = dst_paddr & 15;
922 
923 		if (src_tpage)
924 			memcpy(page_address(dst_tpage) + dst_offset,
925 			       page_address(src_tpage), size);
926 		else {
927 			if (copy_from_user(page_address(dst_tpage) + dst_offset,
928 					   vaddr, size)) {
929 				ret = -EFAULT;
930 				goto e_free;
931 			}
932 		}
933 
934 		paddr = __sme_page_pa(dst_tpage);
935 		dst_paddr = round_down(dst_paddr, 16);
936 		len = round_up(size, 16);
937 	}
938 
939 	ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
940 
941 e_free:
942 	if (src_tpage)
943 		__free_page(src_tpage);
944 	if (dst_tpage)
945 		__free_page(dst_tpage);
946 	return ret;
947 }
948 
949 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
950 {
951 	unsigned long vaddr, vaddr_end, next_vaddr;
952 	unsigned long dst_vaddr;
953 	struct page **src_p, **dst_p;
954 	struct kvm_sev_dbg debug;
955 	unsigned long n;
956 	unsigned int size;
957 	int ret;
958 
959 	if (!sev_guest(kvm))
960 		return -ENOTTY;
961 
962 	if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
963 		return -EFAULT;
964 
965 	if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
966 		return -EINVAL;
967 	if (!debug.dst_uaddr)
968 		return -EINVAL;
969 
970 	vaddr = debug.src_uaddr;
971 	size = debug.len;
972 	vaddr_end = vaddr + size;
973 	dst_vaddr = debug.dst_uaddr;
974 
975 	for (; vaddr < vaddr_end; vaddr = next_vaddr) {
976 		int len, s_off, d_off;
977 
978 		/* lock userspace source and destination page */
979 		src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
980 		if (IS_ERR(src_p))
981 			return PTR_ERR(src_p);
982 
983 		dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
984 		if (IS_ERR(dst_p)) {
985 			sev_unpin_memory(kvm, src_p, n);
986 			return PTR_ERR(dst_p);
987 		}
988 
989 		/*
990 		 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify
991 		 * the pages; flush the destination too so that future accesses do not
992 		 * see stale data.
993 		 */
994 		sev_clflush_pages(src_p, 1);
995 		sev_clflush_pages(dst_p, 1);
996 
997 		/*
998 		 * Since user buffer may not be page aligned, calculate the
999 		 * offset within the page.
1000 		 */
1001 		s_off = vaddr & ~PAGE_MASK;
1002 		d_off = dst_vaddr & ~PAGE_MASK;
1003 		len = min_t(size_t, (PAGE_SIZE - s_off), size);
1004 
1005 		if (dec)
1006 			ret = __sev_dbg_decrypt_user(kvm,
1007 						     __sme_page_pa(src_p[0]) + s_off,
1008 						     (void __user *)dst_vaddr,
1009 						     __sme_page_pa(dst_p[0]) + d_off,
1010 						     len, &argp->error);
1011 		else
1012 			ret = __sev_dbg_encrypt_user(kvm,
1013 						     __sme_page_pa(src_p[0]) + s_off,
1014 						     (void __user *)vaddr,
1015 						     __sme_page_pa(dst_p[0]) + d_off,
1016 						     (void __user *)dst_vaddr,
1017 						     len, &argp->error);
1018 
1019 		sev_unpin_memory(kvm, src_p, n);
1020 		sev_unpin_memory(kvm, dst_p, n);
1021 
1022 		if (ret)
1023 			goto err;
1024 
1025 		next_vaddr = vaddr + len;
1026 		dst_vaddr = dst_vaddr + len;
1027 		size -= len;
1028 	}
1029 err:
1030 	return ret;
1031 }
1032 
1033 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
1034 {
1035 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1036 	struct sev_data_launch_secret data;
1037 	struct kvm_sev_launch_secret params;
1038 	struct page **pages;
1039 	void *blob, *hdr;
1040 	unsigned long n, i;
1041 	int ret, offset;
1042 
1043 	if (!sev_guest(kvm))
1044 		return -ENOTTY;
1045 
1046 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
1047 		return -EFAULT;
1048 
1049 	pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
1050 	if (IS_ERR(pages))
1051 		return PTR_ERR(pages);
1052 
1053 	/*
1054 	 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in
1055 	 * place; the cache may contain the data that was written unencrypted.
1056 	 */
1057 	sev_clflush_pages(pages, n);
1058 
1059 	/*
1060 	 * The secret must be copied into contiguous memory region, lets verify
1061 	 * that userspace memory pages are contiguous before we issue command.
1062 	 */
1063 	if (get_num_contig_pages(0, pages, n) != n) {
1064 		ret = -EINVAL;
1065 		goto e_unpin_memory;
1066 	}
1067 
1068 	memset(&data, 0, sizeof(data));
1069 
1070 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1071 	data.guest_address = __sme_page_pa(pages[0]) + offset;
1072 	data.guest_len = params.guest_len;
1073 
1074 	blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1075 	if (IS_ERR(blob)) {
1076 		ret = PTR_ERR(blob);
1077 		goto e_unpin_memory;
1078 	}
1079 
1080 	data.trans_address = __psp_pa(blob);
1081 	data.trans_len = params.trans_len;
1082 
1083 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1084 	if (IS_ERR(hdr)) {
1085 		ret = PTR_ERR(hdr);
1086 		goto e_free_blob;
1087 	}
1088 	data.hdr_address = __psp_pa(hdr);
1089 	data.hdr_len = params.hdr_len;
1090 
1091 	data.handle = sev->handle;
1092 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, &data, &argp->error);
1093 
1094 	kfree(hdr);
1095 
1096 e_free_blob:
1097 	kfree(blob);
1098 e_unpin_memory:
1099 	/* content of memory is updated, mark pages dirty */
1100 	for (i = 0; i < n; i++) {
1101 		set_page_dirty_lock(pages[i]);
1102 		mark_page_accessed(pages[i]);
1103 	}
1104 	sev_unpin_memory(kvm, pages, n);
1105 	return ret;
1106 }
1107 
1108 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp)
1109 {
1110 	void __user *report = (void __user *)(uintptr_t)argp->data;
1111 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1112 	struct sev_data_attestation_report data;
1113 	struct kvm_sev_attestation_report params;
1114 	void __user *p;
1115 	void *blob = NULL;
1116 	int ret;
1117 
1118 	if (!sev_guest(kvm))
1119 		return -ENOTTY;
1120 
1121 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
1122 		return -EFAULT;
1123 
1124 	memset(&data, 0, sizeof(data));
1125 
1126 	/* User wants to query the blob length */
1127 	if (!params.len)
1128 		goto cmd;
1129 
1130 	p = (void __user *)(uintptr_t)params.uaddr;
1131 	if (p) {
1132 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
1133 			return -EINVAL;
1134 
1135 		blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
1136 		if (!blob)
1137 			return -ENOMEM;
1138 
1139 		data.address = __psp_pa(blob);
1140 		data.len = params.len;
1141 		memcpy(data.mnonce, params.mnonce, sizeof(params.mnonce));
1142 	}
1143 cmd:
1144 	data.handle = sev->handle;
1145 	ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, &data, &argp->error);
1146 	/*
1147 	 * If we query the session length, FW responded with expected data.
1148 	 */
1149 	if (!params.len)
1150 		goto done;
1151 
1152 	if (ret)
1153 		goto e_free_blob;
1154 
1155 	if (blob) {
1156 		if (copy_to_user(p, blob, params.len))
1157 			ret = -EFAULT;
1158 	}
1159 
1160 done:
1161 	params.len = data.len;
1162 	if (copy_to_user(report, &params, sizeof(params)))
1163 		ret = -EFAULT;
1164 e_free_blob:
1165 	kfree(blob);
1166 	return ret;
1167 }
1168 
1169 /* Userspace wants to query session length. */
1170 static int
1171 __sev_send_start_query_session_length(struct kvm *kvm, struct kvm_sev_cmd *argp,
1172 				      struct kvm_sev_send_start *params)
1173 {
1174 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1175 	struct sev_data_send_start data;
1176 	int ret;
1177 
1178 	memset(&data, 0, sizeof(data));
1179 	data.handle = sev->handle;
1180 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1181 
1182 	params->session_len = data.session_len;
1183 	if (copy_to_user((void __user *)(uintptr_t)argp->data, params,
1184 				sizeof(struct kvm_sev_send_start)))
1185 		ret = -EFAULT;
1186 
1187 	return ret;
1188 }
1189 
1190 static int sev_send_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1191 {
1192 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1193 	struct sev_data_send_start data;
1194 	struct kvm_sev_send_start params;
1195 	void *amd_certs, *session_data;
1196 	void *pdh_cert, *plat_certs;
1197 	int ret;
1198 
1199 	if (!sev_guest(kvm))
1200 		return -ENOTTY;
1201 
1202 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1203 				sizeof(struct kvm_sev_send_start)))
1204 		return -EFAULT;
1205 
1206 	/* if session_len is zero, userspace wants to query the session length */
1207 	if (!params.session_len)
1208 		return __sev_send_start_query_session_length(kvm, argp,
1209 				&params);
1210 
1211 	/* some sanity checks */
1212 	if (!params.pdh_cert_uaddr || !params.pdh_cert_len ||
1213 	    !params.session_uaddr || params.session_len > SEV_FW_BLOB_MAX_SIZE)
1214 		return -EINVAL;
1215 
1216 	/* allocate the memory to hold the session data blob */
1217 	session_data = kzalloc(params.session_len, GFP_KERNEL_ACCOUNT);
1218 	if (!session_data)
1219 		return -ENOMEM;
1220 
1221 	/* copy the certificate blobs from userspace */
1222 	pdh_cert = psp_copy_user_blob(params.pdh_cert_uaddr,
1223 				params.pdh_cert_len);
1224 	if (IS_ERR(pdh_cert)) {
1225 		ret = PTR_ERR(pdh_cert);
1226 		goto e_free_session;
1227 	}
1228 
1229 	plat_certs = psp_copy_user_blob(params.plat_certs_uaddr,
1230 				params.plat_certs_len);
1231 	if (IS_ERR(plat_certs)) {
1232 		ret = PTR_ERR(plat_certs);
1233 		goto e_free_pdh;
1234 	}
1235 
1236 	amd_certs = psp_copy_user_blob(params.amd_certs_uaddr,
1237 				params.amd_certs_len);
1238 	if (IS_ERR(amd_certs)) {
1239 		ret = PTR_ERR(amd_certs);
1240 		goto e_free_plat_cert;
1241 	}
1242 
1243 	/* populate the FW SEND_START field with system physical address */
1244 	memset(&data, 0, sizeof(data));
1245 	data.pdh_cert_address = __psp_pa(pdh_cert);
1246 	data.pdh_cert_len = params.pdh_cert_len;
1247 	data.plat_certs_address = __psp_pa(plat_certs);
1248 	data.plat_certs_len = params.plat_certs_len;
1249 	data.amd_certs_address = __psp_pa(amd_certs);
1250 	data.amd_certs_len = params.amd_certs_len;
1251 	data.session_address = __psp_pa(session_data);
1252 	data.session_len = params.session_len;
1253 	data.handle = sev->handle;
1254 
1255 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1256 
1257 	if (!ret && copy_to_user((void __user *)(uintptr_t)params.session_uaddr,
1258 			session_data, params.session_len)) {
1259 		ret = -EFAULT;
1260 		goto e_free_amd_cert;
1261 	}
1262 
1263 	params.policy = data.policy;
1264 	params.session_len = data.session_len;
1265 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params,
1266 				sizeof(struct kvm_sev_send_start)))
1267 		ret = -EFAULT;
1268 
1269 e_free_amd_cert:
1270 	kfree(amd_certs);
1271 e_free_plat_cert:
1272 	kfree(plat_certs);
1273 e_free_pdh:
1274 	kfree(pdh_cert);
1275 e_free_session:
1276 	kfree(session_data);
1277 	return ret;
1278 }
1279 
1280 /* Userspace wants to query either header or trans length. */
1281 static int
1282 __sev_send_update_data_query_lengths(struct kvm *kvm, struct kvm_sev_cmd *argp,
1283 				     struct kvm_sev_send_update_data *params)
1284 {
1285 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1286 	struct sev_data_send_update_data data;
1287 	int ret;
1288 
1289 	memset(&data, 0, sizeof(data));
1290 	data.handle = sev->handle;
1291 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1292 
1293 	params->hdr_len = data.hdr_len;
1294 	params->trans_len = data.trans_len;
1295 
1296 	if (copy_to_user((void __user *)(uintptr_t)argp->data, params,
1297 			 sizeof(struct kvm_sev_send_update_data)))
1298 		ret = -EFAULT;
1299 
1300 	return ret;
1301 }
1302 
1303 static int sev_send_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1304 {
1305 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1306 	struct sev_data_send_update_data data;
1307 	struct kvm_sev_send_update_data params;
1308 	void *hdr, *trans_data;
1309 	struct page **guest_page;
1310 	unsigned long n;
1311 	int ret, offset;
1312 
1313 	if (!sev_guest(kvm))
1314 		return -ENOTTY;
1315 
1316 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1317 			sizeof(struct kvm_sev_send_update_data)))
1318 		return -EFAULT;
1319 
1320 	/* userspace wants to query either header or trans length */
1321 	if (!params.trans_len || !params.hdr_len)
1322 		return __sev_send_update_data_query_lengths(kvm, argp, &params);
1323 
1324 	if (!params.trans_uaddr || !params.guest_uaddr ||
1325 	    !params.guest_len || !params.hdr_uaddr)
1326 		return -EINVAL;
1327 
1328 	/* Check if we are crossing the page boundary */
1329 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1330 	if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1331 		return -EINVAL;
1332 
1333 	/* Pin guest memory */
1334 	guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1335 				    PAGE_SIZE, &n, 0);
1336 	if (IS_ERR(guest_page))
1337 		return PTR_ERR(guest_page);
1338 
1339 	/* allocate memory for header and transport buffer */
1340 	ret = -ENOMEM;
1341 	hdr = kzalloc(params.hdr_len, GFP_KERNEL_ACCOUNT);
1342 	if (!hdr)
1343 		goto e_unpin;
1344 
1345 	trans_data = kzalloc(params.trans_len, GFP_KERNEL_ACCOUNT);
1346 	if (!trans_data)
1347 		goto e_free_hdr;
1348 
1349 	memset(&data, 0, sizeof(data));
1350 	data.hdr_address = __psp_pa(hdr);
1351 	data.hdr_len = params.hdr_len;
1352 	data.trans_address = __psp_pa(trans_data);
1353 	data.trans_len = params.trans_len;
1354 
1355 	/* The SEND_UPDATE_DATA command requires C-bit to be always set. */
1356 	data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1357 	data.guest_address |= sev_me_mask;
1358 	data.guest_len = params.guest_len;
1359 	data.handle = sev->handle;
1360 
1361 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1362 
1363 	if (ret)
1364 		goto e_free_trans_data;
1365 
1366 	/* copy transport buffer to user space */
1367 	if (copy_to_user((void __user *)(uintptr_t)params.trans_uaddr,
1368 			 trans_data, params.trans_len)) {
1369 		ret = -EFAULT;
1370 		goto e_free_trans_data;
1371 	}
1372 
1373 	/* Copy packet header to userspace. */
1374 	if (copy_to_user((void __user *)(uintptr_t)params.hdr_uaddr, hdr,
1375 			 params.hdr_len))
1376 		ret = -EFAULT;
1377 
1378 e_free_trans_data:
1379 	kfree(trans_data);
1380 e_free_hdr:
1381 	kfree(hdr);
1382 e_unpin:
1383 	sev_unpin_memory(kvm, guest_page, n);
1384 
1385 	return ret;
1386 }
1387 
1388 static int sev_send_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1389 {
1390 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1391 	struct sev_data_send_finish data;
1392 
1393 	if (!sev_guest(kvm))
1394 		return -ENOTTY;
1395 
1396 	data.handle = sev->handle;
1397 	return sev_issue_cmd(kvm, SEV_CMD_SEND_FINISH, &data, &argp->error);
1398 }
1399 
1400 static int sev_send_cancel(struct kvm *kvm, struct kvm_sev_cmd *argp)
1401 {
1402 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1403 	struct sev_data_send_cancel data;
1404 
1405 	if (!sev_guest(kvm))
1406 		return -ENOTTY;
1407 
1408 	data.handle = sev->handle;
1409 	return sev_issue_cmd(kvm, SEV_CMD_SEND_CANCEL, &data, &argp->error);
1410 }
1411 
1412 static int sev_receive_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1413 {
1414 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1415 	struct sev_data_receive_start start;
1416 	struct kvm_sev_receive_start params;
1417 	int *error = &argp->error;
1418 	void *session_data;
1419 	void *pdh_data;
1420 	int ret;
1421 
1422 	if (!sev_guest(kvm))
1423 		return -ENOTTY;
1424 
1425 	/* Get parameter from the userspace */
1426 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1427 			sizeof(struct kvm_sev_receive_start)))
1428 		return -EFAULT;
1429 
1430 	/* some sanity checks */
1431 	if (!params.pdh_uaddr || !params.pdh_len ||
1432 	    !params.session_uaddr || !params.session_len)
1433 		return -EINVAL;
1434 
1435 	pdh_data = psp_copy_user_blob(params.pdh_uaddr, params.pdh_len);
1436 	if (IS_ERR(pdh_data))
1437 		return PTR_ERR(pdh_data);
1438 
1439 	session_data = psp_copy_user_blob(params.session_uaddr,
1440 			params.session_len);
1441 	if (IS_ERR(session_data)) {
1442 		ret = PTR_ERR(session_data);
1443 		goto e_free_pdh;
1444 	}
1445 
1446 	memset(&start, 0, sizeof(start));
1447 	start.handle = params.handle;
1448 	start.policy = params.policy;
1449 	start.pdh_cert_address = __psp_pa(pdh_data);
1450 	start.pdh_cert_len = params.pdh_len;
1451 	start.session_address = __psp_pa(session_data);
1452 	start.session_len = params.session_len;
1453 
1454 	/* create memory encryption context */
1455 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_RECEIVE_START, &start,
1456 				error);
1457 	if (ret)
1458 		goto e_free_session;
1459 
1460 	/* Bind ASID to this guest */
1461 	ret = sev_bind_asid(kvm, start.handle, error);
1462 	if (ret) {
1463 		sev_decommission(start.handle);
1464 		goto e_free_session;
1465 	}
1466 
1467 	params.handle = start.handle;
1468 	if (copy_to_user((void __user *)(uintptr_t)argp->data,
1469 			 &params, sizeof(struct kvm_sev_receive_start))) {
1470 		ret = -EFAULT;
1471 		sev_unbind_asid(kvm, start.handle);
1472 		goto e_free_session;
1473 	}
1474 
1475     	sev->handle = start.handle;
1476 	sev->fd = argp->sev_fd;
1477 
1478 e_free_session:
1479 	kfree(session_data);
1480 e_free_pdh:
1481 	kfree(pdh_data);
1482 
1483 	return ret;
1484 }
1485 
1486 static int sev_receive_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1487 {
1488 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1489 	struct kvm_sev_receive_update_data params;
1490 	struct sev_data_receive_update_data data;
1491 	void *hdr = NULL, *trans = NULL;
1492 	struct page **guest_page;
1493 	unsigned long n;
1494 	int ret, offset;
1495 
1496 	if (!sev_guest(kvm))
1497 		return -EINVAL;
1498 
1499 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1500 			sizeof(struct kvm_sev_receive_update_data)))
1501 		return -EFAULT;
1502 
1503 	if (!params.hdr_uaddr || !params.hdr_len ||
1504 	    !params.guest_uaddr || !params.guest_len ||
1505 	    !params.trans_uaddr || !params.trans_len)
1506 		return -EINVAL;
1507 
1508 	/* Check if we are crossing the page boundary */
1509 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1510 	if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1511 		return -EINVAL;
1512 
1513 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1514 	if (IS_ERR(hdr))
1515 		return PTR_ERR(hdr);
1516 
1517 	trans = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1518 	if (IS_ERR(trans)) {
1519 		ret = PTR_ERR(trans);
1520 		goto e_free_hdr;
1521 	}
1522 
1523 	memset(&data, 0, sizeof(data));
1524 	data.hdr_address = __psp_pa(hdr);
1525 	data.hdr_len = params.hdr_len;
1526 	data.trans_address = __psp_pa(trans);
1527 	data.trans_len = params.trans_len;
1528 
1529 	/* Pin guest memory */
1530 	guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1531 				    PAGE_SIZE, &n, 1);
1532 	if (IS_ERR(guest_page)) {
1533 		ret = PTR_ERR(guest_page);
1534 		goto e_free_trans;
1535 	}
1536 
1537 	/*
1538 	 * Flush (on non-coherent CPUs) before RECEIVE_UPDATE_DATA, the PSP
1539 	 * encrypts the written data with the guest's key, and the cache may
1540 	 * contain dirty, unencrypted data.
1541 	 */
1542 	sev_clflush_pages(guest_page, n);
1543 
1544 	/* The RECEIVE_UPDATE_DATA command requires C-bit to be always set. */
1545 	data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1546 	data.guest_address |= sev_me_mask;
1547 	data.guest_len = params.guest_len;
1548 	data.handle = sev->handle;
1549 
1550 	ret = sev_issue_cmd(kvm, SEV_CMD_RECEIVE_UPDATE_DATA, &data,
1551 				&argp->error);
1552 
1553 	sev_unpin_memory(kvm, guest_page, n);
1554 
1555 e_free_trans:
1556 	kfree(trans);
1557 e_free_hdr:
1558 	kfree(hdr);
1559 
1560 	return ret;
1561 }
1562 
1563 static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1564 {
1565 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1566 	struct sev_data_receive_finish data;
1567 
1568 	if (!sev_guest(kvm))
1569 		return -ENOTTY;
1570 
1571 	data.handle = sev->handle;
1572 	return sev_issue_cmd(kvm, SEV_CMD_RECEIVE_FINISH, &data, &argp->error);
1573 }
1574 
1575 static bool is_cmd_allowed_from_mirror(u32 cmd_id)
1576 {
1577 	/*
1578 	 * Allow mirrors VM to call KVM_SEV_LAUNCH_UPDATE_VMSA to enable SEV-ES
1579 	 * active mirror VMs. Also allow the debugging and status commands.
1580 	 */
1581 	if (cmd_id == KVM_SEV_LAUNCH_UPDATE_VMSA ||
1582 	    cmd_id == KVM_SEV_GUEST_STATUS || cmd_id == KVM_SEV_DBG_DECRYPT ||
1583 	    cmd_id == KVM_SEV_DBG_ENCRYPT)
1584 		return true;
1585 
1586 	return false;
1587 }
1588 
1589 static int sev_lock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1590 {
1591 	struct kvm_sev_info *dst_sev = &to_kvm_svm(dst_kvm)->sev_info;
1592 	struct kvm_sev_info *src_sev = &to_kvm_svm(src_kvm)->sev_info;
1593 	int r = -EBUSY;
1594 
1595 	if (dst_kvm == src_kvm)
1596 		return -EINVAL;
1597 
1598 	/*
1599 	 * Bail if these VMs are already involved in a migration to avoid
1600 	 * deadlock between two VMs trying to migrate to/from each other.
1601 	 */
1602 	if (atomic_cmpxchg_acquire(&dst_sev->migration_in_progress, 0, 1))
1603 		return -EBUSY;
1604 
1605 	if (atomic_cmpxchg_acquire(&src_sev->migration_in_progress, 0, 1))
1606 		goto release_dst;
1607 
1608 	r = -EINTR;
1609 	if (mutex_lock_killable(&dst_kvm->lock))
1610 		goto release_src;
1611 	if (mutex_lock_killable_nested(&src_kvm->lock, SINGLE_DEPTH_NESTING))
1612 		goto unlock_dst;
1613 	return 0;
1614 
1615 unlock_dst:
1616 	mutex_unlock(&dst_kvm->lock);
1617 release_src:
1618 	atomic_set_release(&src_sev->migration_in_progress, 0);
1619 release_dst:
1620 	atomic_set_release(&dst_sev->migration_in_progress, 0);
1621 	return r;
1622 }
1623 
1624 static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1625 {
1626 	struct kvm_sev_info *dst_sev = &to_kvm_svm(dst_kvm)->sev_info;
1627 	struct kvm_sev_info *src_sev = &to_kvm_svm(src_kvm)->sev_info;
1628 
1629 	mutex_unlock(&dst_kvm->lock);
1630 	mutex_unlock(&src_kvm->lock);
1631 	atomic_set_release(&dst_sev->migration_in_progress, 0);
1632 	atomic_set_release(&src_sev->migration_in_progress, 0);
1633 }
1634 
1635 /* vCPU mutex subclasses.  */
1636 enum sev_migration_role {
1637 	SEV_MIGRATION_SOURCE = 0,
1638 	SEV_MIGRATION_TARGET,
1639 	SEV_NR_MIGRATION_ROLES,
1640 };
1641 
1642 static int sev_lock_vcpus_for_migration(struct kvm *kvm,
1643 					enum sev_migration_role role)
1644 {
1645 	struct kvm_vcpu *vcpu;
1646 	unsigned long i, j;
1647 
1648 	kvm_for_each_vcpu(i, vcpu, kvm) {
1649 		if (mutex_lock_killable_nested(&vcpu->mutex, role))
1650 			goto out_unlock;
1651 
1652 #ifdef CONFIG_PROVE_LOCKING
1653 		if (!i)
1654 			/*
1655 			 * Reset the role to one that avoids colliding with
1656 			 * the role used for the first vcpu mutex.
1657 			 */
1658 			role = SEV_NR_MIGRATION_ROLES;
1659 		else
1660 			mutex_release(&vcpu->mutex.dep_map, _THIS_IP_);
1661 #endif
1662 	}
1663 
1664 	return 0;
1665 
1666 out_unlock:
1667 
1668 	kvm_for_each_vcpu(j, vcpu, kvm) {
1669 		if (i == j)
1670 			break;
1671 
1672 #ifdef CONFIG_PROVE_LOCKING
1673 		if (j)
1674 			mutex_acquire(&vcpu->mutex.dep_map, role, 0, _THIS_IP_);
1675 #endif
1676 
1677 		mutex_unlock(&vcpu->mutex);
1678 	}
1679 	return -EINTR;
1680 }
1681 
1682 static void sev_unlock_vcpus_for_migration(struct kvm *kvm)
1683 {
1684 	struct kvm_vcpu *vcpu;
1685 	unsigned long i;
1686 	bool first = true;
1687 
1688 	kvm_for_each_vcpu(i, vcpu, kvm) {
1689 		if (first)
1690 			first = false;
1691 		else
1692 			mutex_acquire(&vcpu->mutex.dep_map,
1693 				      SEV_NR_MIGRATION_ROLES, 0, _THIS_IP_);
1694 
1695 		mutex_unlock(&vcpu->mutex);
1696 	}
1697 }
1698 
1699 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
1700 {
1701 	struct kvm_sev_info *dst = &to_kvm_svm(dst_kvm)->sev_info;
1702 	struct kvm_sev_info *src = &to_kvm_svm(src_kvm)->sev_info;
1703 	struct kvm_vcpu *dst_vcpu, *src_vcpu;
1704 	struct vcpu_svm *dst_svm, *src_svm;
1705 	struct kvm_sev_info *mirror;
1706 	unsigned long i;
1707 
1708 	dst->active = true;
1709 	dst->asid = src->asid;
1710 	dst->handle = src->handle;
1711 	dst->pages_locked = src->pages_locked;
1712 	dst->enc_context_owner = src->enc_context_owner;
1713 	dst->es_active = src->es_active;
1714 
1715 	src->asid = 0;
1716 	src->active = false;
1717 	src->handle = 0;
1718 	src->pages_locked = 0;
1719 	src->enc_context_owner = NULL;
1720 	src->es_active = false;
1721 
1722 	list_cut_before(&dst->regions_list, &src->regions_list, &src->regions_list);
1723 
1724 	/*
1725 	 * If this VM has mirrors, "transfer" each mirror's refcount of the
1726 	 * source to the destination (this KVM).  The caller holds a reference
1727 	 * to the source, so there's no danger of use-after-free.
1728 	 */
1729 	list_cut_before(&dst->mirror_vms, &src->mirror_vms, &src->mirror_vms);
1730 	list_for_each_entry(mirror, &dst->mirror_vms, mirror_entry) {
1731 		kvm_get_kvm(dst_kvm);
1732 		kvm_put_kvm(src_kvm);
1733 		mirror->enc_context_owner = dst_kvm;
1734 	}
1735 
1736 	/*
1737 	 * If this VM is a mirror, remove the old mirror from the owners list
1738 	 * and add the new mirror to the list.
1739 	 */
1740 	if (is_mirroring_enc_context(dst_kvm)) {
1741 		struct kvm_sev_info *owner_sev_info =
1742 			&to_kvm_svm(dst->enc_context_owner)->sev_info;
1743 
1744 		list_del(&src->mirror_entry);
1745 		list_add_tail(&dst->mirror_entry, &owner_sev_info->mirror_vms);
1746 	}
1747 
1748 	kvm_for_each_vcpu(i, dst_vcpu, dst_kvm) {
1749 		dst_svm = to_svm(dst_vcpu);
1750 
1751 		sev_init_vmcb(dst_svm);
1752 
1753 		if (!dst->es_active)
1754 			continue;
1755 
1756 		/*
1757 		 * Note, the source is not required to have the same number of
1758 		 * vCPUs as the destination when migrating a vanilla SEV VM.
1759 		 */
1760 		src_vcpu = kvm_get_vcpu(src_kvm, i);
1761 		src_svm = to_svm(src_vcpu);
1762 
1763 		/*
1764 		 * Transfer VMSA and GHCB state to the destination.  Nullify and
1765 		 * clear source fields as appropriate, the state now belongs to
1766 		 * the destination.
1767 		 */
1768 		memcpy(&dst_svm->sev_es, &src_svm->sev_es, sizeof(src_svm->sev_es));
1769 		dst_svm->vmcb->control.ghcb_gpa = src_svm->vmcb->control.ghcb_gpa;
1770 		dst_svm->vmcb->control.vmsa_pa = src_svm->vmcb->control.vmsa_pa;
1771 		dst_vcpu->arch.guest_state_protected = true;
1772 
1773 		memset(&src_svm->sev_es, 0, sizeof(src_svm->sev_es));
1774 		src_svm->vmcb->control.ghcb_gpa = INVALID_PAGE;
1775 		src_svm->vmcb->control.vmsa_pa = INVALID_PAGE;
1776 		src_vcpu->arch.guest_state_protected = false;
1777 	}
1778 }
1779 
1780 static int sev_check_source_vcpus(struct kvm *dst, struct kvm *src)
1781 {
1782 	struct kvm_vcpu *src_vcpu;
1783 	unsigned long i;
1784 
1785 	if (!sev_es_guest(src))
1786 		return 0;
1787 
1788 	if (atomic_read(&src->online_vcpus) != atomic_read(&dst->online_vcpus))
1789 		return -EINVAL;
1790 
1791 	kvm_for_each_vcpu(i, src_vcpu, src) {
1792 		if (!src_vcpu->arch.guest_state_protected)
1793 			return -EINVAL;
1794 	}
1795 
1796 	return 0;
1797 }
1798 
1799 int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
1800 {
1801 	struct kvm_sev_info *dst_sev = &to_kvm_svm(kvm)->sev_info;
1802 	struct kvm_sev_info *src_sev, *cg_cleanup_sev;
1803 	struct fd f = fdget(source_fd);
1804 	struct kvm *source_kvm;
1805 	bool charged = false;
1806 	int ret;
1807 
1808 	if (!f.file)
1809 		return -EBADF;
1810 
1811 	if (!file_is_kvm(f.file)) {
1812 		ret = -EBADF;
1813 		goto out_fput;
1814 	}
1815 
1816 	source_kvm = f.file->private_data;
1817 	ret = sev_lock_two_vms(kvm, source_kvm);
1818 	if (ret)
1819 		goto out_fput;
1820 
1821 	if (sev_guest(kvm) || !sev_guest(source_kvm)) {
1822 		ret = -EINVAL;
1823 		goto out_unlock;
1824 	}
1825 
1826 	src_sev = &to_kvm_svm(source_kvm)->sev_info;
1827 
1828 	dst_sev->misc_cg = get_current_misc_cg();
1829 	cg_cleanup_sev = dst_sev;
1830 	if (dst_sev->misc_cg != src_sev->misc_cg) {
1831 		ret = sev_misc_cg_try_charge(dst_sev);
1832 		if (ret)
1833 			goto out_dst_cgroup;
1834 		charged = true;
1835 	}
1836 
1837 	ret = sev_lock_vcpus_for_migration(kvm, SEV_MIGRATION_SOURCE);
1838 	if (ret)
1839 		goto out_dst_cgroup;
1840 	ret = sev_lock_vcpus_for_migration(source_kvm, SEV_MIGRATION_TARGET);
1841 	if (ret)
1842 		goto out_dst_vcpu;
1843 
1844 	ret = sev_check_source_vcpus(kvm, source_kvm);
1845 	if (ret)
1846 		goto out_source_vcpu;
1847 
1848 	sev_migrate_from(kvm, source_kvm);
1849 	kvm_vm_dead(source_kvm);
1850 	cg_cleanup_sev = src_sev;
1851 	ret = 0;
1852 
1853 out_source_vcpu:
1854 	sev_unlock_vcpus_for_migration(source_kvm);
1855 out_dst_vcpu:
1856 	sev_unlock_vcpus_for_migration(kvm);
1857 out_dst_cgroup:
1858 	/* Operates on the source on success, on the destination on failure.  */
1859 	if (charged)
1860 		sev_misc_cg_uncharge(cg_cleanup_sev);
1861 	put_misc_cg(cg_cleanup_sev->misc_cg);
1862 	cg_cleanup_sev->misc_cg = NULL;
1863 out_unlock:
1864 	sev_unlock_two_vms(kvm, source_kvm);
1865 out_fput:
1866 	fdput(f);
1867 	return ret;
1868 }
1869 
1870 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
1871 {
1872 	struct kvm_sev_cmd sev_cmd;
1873 	int r;
1874 
1875 	if (!sev_enabled)
1876 		return -ENOTTY;
1877 
1878 	if (!argp)
1879 		return 0;
1880 
1881 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
1882 		return -EFAULT;
1883 
1884 	mutex_lock(&kvm->lock);
1885 
1886 	/* Only the enc_context_owner handles some memory enc operations. */
1887 	if (is_mirroring_enc_context(kvm) &&
1888 	    !is_cmd_allowed_from_mirror(sev_cmd.id)) {
1889 		r = -EINVAL;
1890 		goto out;
1891 	}
1892 
1893 	switch (sev_cmd.id) {
1894 	case KVM_SEV_ES_INIT:
1895 		if (!sev_es_enabled) {
1896 			r = -ENOTTY;
1897 			goto out;
1898 		}
1899 		fallthrough;
1900 	case KVM_SEV_INIT:
1901 		r = sev_guest_init(kvm, &sev_cmd);
1902 		break;
1903 	case KVM_SEV_LAUNCH_START:
1904 		r = sev_launch_start(kvm, &sev_cmd);
1905 		break;
1906 	case KVM_SEV_LAUNCH_UPDATE_DATA:
1907 		r = sev_launch_update_data(kvm, &sev_cmd);
1908 		break;
1909 	case KVM_SEV_LAUNCH_UPDATE_VMSA:
1910 		r = sev_launch_update_vmsa(kvm, &sev_cmd);
1911 		break;
1912 	case KVM_SEV_LAUNCH_MEASURE:
1913 		r = sev_launch_measure(kvm, &sev_cmd);
1914 		break;
1915 	case KVM_SEV_LAUNCH_FINISH:
1916 		r = sev_launch_finish(kvm, &sev_cmd);
1917 		break;
1918 	case KVM_SEV_GUEST_STATUS:
1919 		r = sev_guest_status(kvm, &sev_cmd);
1920 		break;
1921 	case KVM_SEV_DBG_DECRYPT:
1922 		r = sev_dbg_crypt(kvm, &sev_cmd, true);
1923 		break;
1924 	case KVM_SEV_DBG_ENCRYPT:
1925 		r = sev_dbg_crypt(kvm, &sev_cmd, false);
1926 		break;
1927 	case KVM_SEV_LAUNCH_SECRET:
1928 		r = sev_launch_secret(kvm, &sev_cmd);
1929 		break;
1930 	case KVM_SEV_GET_ATTESTATION_REPORT:
1931 		r = sev_get_attestation_report(kvm, &sev_cmd);
1932 		break;
1933 	case KVM_SEV_SEND_START:
1934 		r = sev_send_start(kvm, &sev_cmd);
1935 		break;
1936 	case KVM_SEV_SEND_UPDATE_DATA:
1937 		r = sev_send_update_data(kvm, &sev_cmd);
1938 		break;
1939 	case KVM_SEV_SEND_FINISH:
1940 		r = sev_send_finish(kvm, &sev_cmd);
1941 		break;
1942 	case KVM_SEV_SEND_CANCEL:
1943 		r = sev_send_cancel(kvm, &sev_cmd);
1944 		break;
1945 	case KVM_SEV_RECEIVE_START:
1946 		r = sev_receive_start(kvm, &sev_cmd);
1947 		break;
1948 	case KVM_SEV_RECEIVE_UPDATE_DATA:
1949 		r = sev_receive_update_data(kvm, &sev_cmd);
1950 		break;
1951 	case KVM_SEV_RECEIVE_FINISH:
1952 		r = sev_receive_finish(kvm, &sev_cmd);
1953 		break;
1954 	default:
1955 		r = -EINVAL;
1956 		goto out;
1957 	}
1958 
1959 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
1960 		r = -EFAULT;
1961 
1962 out:
1963 	mutex_unlock(&kvm->lock);
1964 	return r;
1965 }
1966 
1967 int sev_mem_enc_register_region(struct kvm *kvm,
1968 				struct kvm_enc_region *range)
1969 {
1970 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1971 	struct enc_region *region;
1972 	int ret = 0;
1973 
1974 	if (!sev_guest(kvm))
1975 		return -ENOTTY;
1976 
1977 	/* If kvm is mirroring encryption context it isn't responsible for it */
1978 	if (is_mirroring_enc_context(kvm))
1979 		return -EINVAL;
1980 
1981 	if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
1982 		return -EINVAL;
1983 
1984 	region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
1985 	if (!region)
1986 		return -ENOMEM;
1987 
1988 	mutex_lock(&kvm->lock);
1989 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
1990 	if (IS_ERR(region->pages)) {
1991 		ret = PTR_ERR(region->pages);
1992 		mutex_unlock(&kvm->lock);
1993 		goto e_free;
1994 	}
1995 
1996 	/*
1997 	 * The guest may change the memory encryption attribute from C=0 -> C=1
1998 	 * or vice versa for this memory range. Lets make sure caches are
1999 	 * flushed to ensure that guest data gets written into memory with
2000 	 * correct C-bit.  Note, this must be done before dropping kvm->lock,
2001 	 * as region and its array of pages can be freed by a different task
2002 	 * once kvm->lock is released.
2003 	 */
2004 	sev_clflush_pages(region->pages, region->npages);
2005 
2006 	region->uaddr = range->addr;
2007 	region->size = range->size;
2008 
2009 	list_add_tail(&region->list, &sev->regions_list);
2010 	mutex_unlock(&kvm->lock);
2011 
2012 	return ret;
2013 
2014 e_free:
2015 	kfree(region);
2016 	return ret;
2017 }
2018 
2019 static struct enc_region *
2020 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
2021 {
2022 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2023 	struct list_head *head = &sev->regions_list;
2024 	struct enc_region *i;
2025 
2026 	list_for_each_entry(i, head, list) {
2027 		if (i->uaddr == range->addr &&
2028 		    i->size == range->size)
2029 			return i;
2030 	}
2031 
2032 	return NULL;
2033 }
2034 
2035 static void __unregister_enc_region_locked(struct kvm *kvm,
2036 					   struct enc_region *region)
2037 {
2038 	sev_unpin_memory(kvm, region->pages, region->npages);
2039 	list_del(&region->list);
2040 	kfree(region);
2041 }
2042 
2043 int sev_mem_enc_unregister_region(struct kvm *kvm,
2044 				  struct kvm_enc_region *range)
2045 {
2046 	struct enc_region *region;
2047 	int ret;
2048 
2049 	/* If kvm is mirroring encryption context it isn't responsible for it */
2050 	if (is_mirroring_enc_context(kvm))
2051 		return -EINVAL;
2052 
2053 	mutex_lock(&kvm->lock);
2054 
2055 	if (!sev_guest(kvm)) {
2056 		ret = -ENOTTY;
2057 		goto failed;
2058 	}
2059 
2060 	region = find_enc_region(kvm, range);
2061 	if (!region) {
2062 		ret = -EINVAL;
2063 		goto failed;
2064 	}
2065 
2066 	/*
2067 	 * Ensure that all guest tagged cache entries are flushed before
2068 	 * releasing the pages back to the system for use. CLFLUSH will
2069 	 * not do this, so issue a WBINVD.
2070 	 */
2071 	wbinvd_on_all_cpus();
2072 
2073 	__unregister_enc_region_locked(kvm, region);
2074 
2075 	mutex_unlock(&kvm->lock);
2076 	return 0;
2077 
2078 failed:
2079 	mutex_unlock(&kvm->lock);
2080 	return ret;
2081 }
2082 
2083 int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2084 {
2085 	struct fd f = fdget(source_fd);
2086 	struct kvm *source_kvm;
2087 	struct kvm_sev_info *source_sev, *mirror_sev;
2088 	int ret;
2089 
2090 	if (!f.file)
2091 		return -EBADF;
2092 
2093 	if (!file_is_kvm(f.file)) {
2094 		ret = -EBADF;
2095 		goto e_source_fput;
2096 	}
2097 
2098 	source_kvm = f.file->private_data;
2099 	ret = sev_lock_two_vms(kvm, source_kvm);
2100 	if (ret)
2101 		goto e_source_fput;
2102 
2103 	/*
2104 	 * Mirrors of mirrors should work, but let's not get silly.  Also
2105 	 * disallow out-of-band SEV/SEV-ES init if the target is already an
2106 	 * SEV guest, or if vCPUs have been created.  KVM relies on vCPUs being
2107 	 * created after SEV/SEV-ES initialization, e.g. to init intercepts.
2108 	 */
2109 	if (sev_guest(kvm) || !sev_guest(source_kvm) ||
2110 	    is_mirroring_enc_context(source_kvm) || kvm->created_vcpus) {
2111 		ret = -EINVAL;
2112 		goto e_unlock;
2113 	}
2114 
2115 	/*
2116 	 * The mirror kvm holds an enc_context_owner ref so its asid can't
2117 	 * disappear until we're done with it
2118 	 */
2119 	source_sev = &to_kvm_svm(source_kvm)->sev_info;
2120 	kvm_get_kvm(source_kvm);
2121 	mirror_sev = &to_kvm_svm(kvm)->sev_info;
2122 	list_add_tail(&mirror_sev->mirror_entry, &source_sev->mirror_vms);
2123 
2124 	/* Set enc_context_owner and copy its encryption context over */
2125 	mirror_sev->enc_context_owner = source_kvm;
2126 	mirror_sev->active = true;
2127 	mirror_sev->asid = source_sev->asid;
2128 	mirror_sev->fd = source_sev->fd;
2129 	mirror_sev->es_active = source_sev->es_active;
2130 	mirror_sev->handle = source_sev->handle;
2131 	INIT_LIST_HEAD(&mirror_sev->regions_list);
2132 	INIT_LIST_HEAD(&mirror_sev->mirror_vms);
2133 	ret = 0;
2134 
2135 	/*
2136 	 * Do not copy ap_jump_table. Since the mirror does not share the same
2137 	 * KVM contexts as the original, and they may have different
2138 	 * memory-views.
2139 	 */
2140 
2141 e_unlock:
2142 	sev_unlock_two_vms(kvm, source_kvm);
2143 e_source_fput:
2144 	fdput(f);
2145 	return ret;
2146 }
2147 
2148 void sev_vm_destroy(struct kvm *kvm)
2149 {
2150 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2151 	struct list_head *head = &sev->regions_list;
2152 	struct list_head *pos, *q;
2153 
2154 	if (!sev_guest(kvm))
2155 		return;
2156 
2157 	WARN_ON(!list_empty(&sev->mirror_vms));
2158 
2159 	/* If this is a mirror_kvm release the enc_context_owner and skip sev cleanup */
2160 	if (is_mirroring_enc_context(kvm)) {
2161 		struct kvm *owner_kvm = sev->enc_context_owner;
2162 
2163 		mutex_lock(&owner_kvm->lock);
2164 		list_del(&sev->mirror_entry);
2165 		mutex_unlock(&owner_kvm->lock);
2166 		kvm_put_kvm(owner_kvm);
2167 		return;
2168 	}
2169 
2170 	/*
2171 	 * Ensure that all guest tagged cache entries are flushed before
2172 	 * releasing the pages back to the system for use. CLFLUSH will
2173 	 * not do this, so issue a WBINVD.
2174 	 */
2175 	wbinvd_on_all_cpus();
2176 
2177 	/*
2178 	 * if userspace was terminated before unregistering the memory regions
2179 	 * then lets unpin all the registered memory.
2180 	 */
2181 	if (!list_empty(head)) {
2182 		list_for_each_safe(pos, q, head) {
2183 			__unregister_enc_region_locked(kvm,
2184 				list_entry(pos, struct enc_region, list));
2185 			cond_resched();
2186 		}
2187 	}
2188 
2189 	sev_unbind_asid(kvm, sev->handle);
2190 	sev_asid_free(sev);
2191 }
2192 
2193 void __init sev_set_cpu_caps(void)
2194 {
2195 	if (!sev_enabled)
2196 		kvm_cpu_cap_clear(X86_FEATURE_SEV);
2197 	if (!sev_es_enabled)
2198 		kvm_cpu_cap_clear(X86_FEATURE_SEV_ES);
2199 }
2200 
2201 void __init sev_hardware_setup(void)
2202 {
2203 #ifdef CONFIG_KVM_AMD_SEV
2204 	unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count;
2205 	bool sev_es_supported = false;
2206 	bool sev_supported = false;
2207 
2208 	if (!sev_enabled || !npt_enabled || !nrips)
2209 		goto out;
2210 
2211 	/*
2212 	 * SEV must obviously be supported in hardware.  Sanity check that the
2213 	 * CPU supports decode assists, which is mandatory for SEV guests to
2214 	 * support instruction emulation.
2215 	 */
2216 	if (!boot_cpu_has(X86_FEATURE_SEV) ||
2217 	    WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_DECODEASSISTS)))
2218 		goto out;
2219 
2220 	/* Retrieve SEV CPUID information */
2221 	cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
2222 
2223 	/* Set encryption bit location for SEV-ES guests */
2224 	sev_enc_bit = ebx & 0x3f;
2225 
2226 	/* Maximum number of encrypted guests supported simultaneously */
2227 	max_sev_asid = ecx;
2228 	if (!max_sev_asid)
2229 		goto out;
2230 
2231 	/* Minimum ASID value that should be used for SEV guest */
2232 	min_sev_asid = edx;
2233 	sev_me_mask = 1UL << (ebx & 0x3f);
2234 
2235 	/*
2236 	 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap,
2237 	 * even though it's never used, so that the bitmap is indexed by the
2238 	 * actual ASID.
2239 	 */
2240 	nr_asids = max_sev_asid + 1;
2241 	sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
2242 	if (!sev_asid_bitmap)
2243 		goto out;
2244 
2245 	sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
2246 	if (!sev_reclaim_asid_bitmap) {
2247 		bitmap_free(sev_asid_bitmap);
2248 		sev_asid_bitmap = NULL;
2249 		goto out;
2250 	}
2251 
2252 	if (min_sev_asid <= max_sev_asid) {
2253 		sev_asid_count = max_sev_asid - min_sev_asid + 1;
2254 		WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count));
2255 	}
2256 	sev_supported = true;
2257 
2258 	/* SEV-ES support requested? */
2259 	if (!sev_es_enabled)
2260 		goto out;
2261 
2262 	/*
2263 	 * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
2264 	 * instruction stream, i.e. can't emulate in response to a #NPF and
2265 	 * instead relies on #NPF(RSVD) being reflected into the guest as #VC
2266 	 * (the guest can then do a #VMGEXIT to request MMIO emulation).
2267 	 */
2268 	if (!enable_mmio_caching)
2269 		goto out;
2270 
2271 	/* Does the CPU support SEV-ES? */
2272 	if (!boot_cpu_has(X86_FEATURE_SEV_ES))
2273 		goto out;
2274 
2275 	if (!lbrv) {
2276 		WARN_ONCE(!boot_cpu_has(X86_FEATURE_LBRV),
2277 			  "LBRV must be present for SEV-ES support");
2278 		goto out;
2279 	}
2280 
2281 	/* Has the system been allocated ASIDs for SEV-ES? */
2282 	if (min_sev_asid == 1)
2283 		goto out;
2284 
2285 	sev_es_asid_count = min_sev_asid - 1;
2286 	WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count));
2287 	sev_es_supported = true;
2288 
2289 out:
2290 	if (boot_cpu_has(X86_FEATURE_SEV))
2291 		pr_info("SEV %s (ASIDs %u - %u)\n",
2292 			sev_supported ? min_sev_asid <= max_sev_asid ? "enabled" :
2293 								       "unusable" :
2294 								       "disabled",
2295 			min_sev_asid, max_sev_asid);
2296 	if (boot_cpu_has(X86_FEATURE_SEV_ES))
2297 		pr_info("SEV-ES %s (ASIDs %u - %u)\n",
2298 			sev_es_supported ? "enabled" : "disabled",
2299 			min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1);
2300 
2301 	sev_enabled = sev_supported;
2302 	sev_es_enabled = sev_es_supported;
2303 	if (!sev_es_enabled || !cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) ||
2304 	    !cpu_feature_enabled(X86_FEATURE_NO_NESTED_DATA_BP))
2305 		sev_es_debug_swap_enabled = false;
2306 #endif
2307 }
2308 
2309 void sev_hardware_unsetup(void)
2310 {
2311 	if (!sev_enabled)
2312 		return;
2313 
2314 	/* No need to take sev_bitmap_lock, all VMs have been destroyed. */
2315 	sev_flush_asids(1, max_sev_asid);
2316 
2317 	bitmap_free(sev_asid_bitmap);
2318 	bitmap_free(sev_reclaim_asid_bitmap);
2319 
2320 	misc_cg_set_capacity(MISC_CG_RES_SEV, 0);
2321 	misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0);
2322 }
2323 
2324 int sev_cpu_init(struct svm_cpu_data *sd)
2325 {
2326 	if (!sev_enabled)
2327 		return 0;
2328 
2329 	sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL);
2330 	if (!sd->sev_vmcbs)
2331 		return -ENOMEM;
2332 
2333 	return 0;
2334 }
2335 
2336 /*
2337  * Pages used by hardware to hold guest encrypted state must be flushed before
2338  * returning them to the system.
2339  */
2340 static void sev_flush_encrypted_page(struct kvm_vcpu *vcpu, void *va)
2341 {
2342 	unsigned int asid = sev_get_asid(vcpu->kvm);
2343 
2344 	/*
2345 	 * Note!  The address must be a kernel address, as regular page walk
2346 	 * checks are performed by VM_PAGE_FLUSH, i.e. operating on a user
2347 	 * address is non-deterministic and unsafe.  This function deliberately
2348 	 * takes a pointer to deter passing in a user address.
2349 	 */
2350 	unsigned long addr = (unsigned long)va;
2351 
2352 	/*
2353 	 * If CPU enforced cache coherency for encrypted mappings of the
2354 	 * same physical page is supported, use CLFLUSHOPT instead. NOTE: cache
2355 	 * flush is still needed in order to work properly with DMA devices.
2356 	 */
2357 	if (boot_cpu_has(X86_FEATURE_SME_COHERENT)) {
2358 		clflush_cache_range(va, PAGE_SIZE);
2359 		return;
2360 	}
2361 
2362 	/*
2363 	 * VM Page Flush takes a host virtual address and a guest ASID.  Fall
2364 	 * back to WBINVD if this faults so as not to make any problems worse
2365 	 * by leaving stale encrypted data in the cache.
2366 	 */
2367 	if (WARN_ON_ONCE(wrmsrl_safe(MSR_AMD64_VM_PAGE_FLUSH, addr | asid)))
2368 		goto do_wbinvd;
2369 
2370 	return;
2371 
2372 do_wbinvd:
2373 	wbinvd_on_all_cpus();
2374 }
2375 
2376 void sev_guest_memory_reclaimed(struct kvm *kvm)
2377 {
2378 	if (!sev_guest(kvm))
2379 		return;
2380 
2381 	wbinvd_on_all_cpus();
2382 }
2383 
2384 void sev_free_vcpu(struct kvm_vcpu *vcpu)
2385 {
2386 	struct vcpu_svm *svm;
2387 
2388 	if (!sev_es_guest(vcpu->kvm))
2389 		return;
2390 
2391 	svm = to_svm(vcpu);
2392 
2393 	if (vcpu->arch.guest_state_protected)
2394 		sev_flush_encrypted_page(vcpu, svm->sev_es.vmsa);
2395 
2396 	__free_page(virt_to_page(svm->sev_es.vmsa));
2397 
2398 	if (svm->sev_es.ghcb_sa_free)
2399 		kvfree(svm->sev_es.ghcb_sa);
2400 }
2401 
2402 static void dump_ghcb(struct vcpu_svm *svm)
2403 {
2404 	struct ghcb *ghcb = svm->sev_es.ghcb;
2405 	unsigned int nbits;
2406 
2407 	/* Re-use the dump_invalid_vmcb module parameter */
2408 	if (!dump_invalid_vmcb) {
2409 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
2410 		return;
2411 	}
2412 
2413 	nbits = sizeof(ghcb->save.valid_bitmap) * 8;
2414 
2415 	pr_err("GHCB (GPA=%016llx):\n", svm->vmcb->control.ghcb_gpa);
2416 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
2417 	       ghcb->save.sw_exit_code, ghcb_sw_exit_code_is_valid(ghcb));
2418 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
2419 	       ghcb->save.sw_exit_info_1, ghcb_sw_exit_info_1_is_valid(ghcb));
2420 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
2421 	       ghcb->save.sw_exit_info_2, ghcb_sw_exit_info_2_is_valid(ghcb));
2422 	pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
2423 	       ghcb->save.sw_scratch, ghcb_sw_scratch_is_valid(ghcb));
2424 	pr_err("%-20s%*pb\n", "valid_bitmap", nbits, ghcb->save.valid_bitmap);
2425 }
2426 
2427 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
2428 {
2429 	struct kvm_vcpu *vcpu = &svm->vcpu;
2430 	struct ghcb *ghcb = svm->sev_es.ghcb;
2431 
2432 	/*
2433 	 * The GHCB protocol so far allows for the following data
2434 	 * to be returned:
2435 	 *   GPRs RAX, RBX, RCX, RDX
2436 	 *
2437 	 * Copy their values, even if they may not have been written during the
2438 	 * VM-Exit.  It's the guest's responsibility to not consume random data.
2439 	 */
2440 	ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
2441 	ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
2442 	ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
2443 	ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
2444 }
2445 
2446 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
2447 {
2448 	struct vmcb_control_area *control = &svm->vmcb->control;
2449 	struct kvm_vcpu *vcpu = &svm->vcpu;
2450 	struct ghcb *ghcb = svm->sev_es.ghcb;
2451 	u64 exit_code;
2452 
2453 	/*
2454 	 * The GHCB protocol so far allows for the following data
2455 	 * to be supplied:
2456 	 *   GPRs RAX, RBX, RCX, RDX
2457 	 *   XCR0
2458 	 *   CPL
2459 	 *
2460 	 * VMMCALL allows the guest to provide extra registers. KVM also
2461 	 * expects RSI for hypercalls, so include that, too.
2462 	 *
2463 	 * Copy their values to the appropriate location if supplied.
2464 	 */
2465 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
2466 
2467 	BUILD_BUG_ON(sizeof(svm->sev_es.valid_bitmap) != sizeof(ghcb->save.valid_bitmap));
2468 	memcpy(&svm->sev_es.valid_bitmap, &ghcb->save.valid_bitmap, sizeof(ghcb->save.valid_bitmap));
2469 
2470 	vcpu->arch.regs[VCPU_REGS_RAX] = kvm_ghcb_get_rax_if_valid(svm, ghcb);
2471 	vcpu->arch.regs[VCPU_REGS_RBX] = kvm_ghcb_get_rbx_if_valid(svm, ghcb);
2472 	vcpu->arch.regs[VCPU_REGS_RCX] = kvm_ghcb_get_rcx_if_valid(svm, ghcb);
2473 	vcpu->arch.regs[VCPU_REGS_RDX] = kvm_ghcb_get_rdx_if_valid(svm, ghcb);
2474 	vcpu->arch.regs[VCPU_REGS_RSI] = kvm_ghcb_get_rsi_if_valid(svm, ghcb);
2475 
2476 	svm->vmcb->save.cpl = kvm_ghcb_get_cpl_if_valid(svm, ghcb);
2477 
2478 	if (kvm_ghcb_xcr0_is_valid(svm)) {
2479 		vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb);
2480 		kvm_update_cpuid_runtime(vcpu);
2481 	}
2482 
2483 	/* Copy the GHCB exit information into the VMCB fields */
2484 	exit_code = ghcb_get_sw_exit_code(ghcb);
2485 	control->exit_code = lower_32_bits(exit_code);
2486 	control->exit_code_hi = upper_32_bits(exit_code);
2487 	control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb);
2488 	control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb);
2489 	svm->sev_es.sw_scratch = kvm_ghcb_get_sw_scratch_if_valid(svm, ghcb);
2490 
2491 	/* Clear the valid entries fields */
2492 	memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
2493 }
2494 
2495 static u64 kvm_ghcb_get_sw_exit_code(struct vmcb_control_area *control)
2496 {
2497 	return (((u64)control->exit_code_hi) << 32) | control->exit_code;
2498 }
2499 
2500 static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
2501 {
2502 	struct vmcb_control_area *control = &svm->vmcb->control;
2503 	struct kvm_vcpu *vcpu = &svm->vcpu;
2504 	u64 exit_code;
2505 	u64 reason;
2506 
2507 	/*
2508 	 * Retrieve the exit code now even though it may not be marked valid
2509 	 * as it could help with debugging.
2510 	 */
2511 	exit_code = kvm_ghcb_get_sw_exit_code(control);
2512 
2513 	/* Only GHCB Usage code 0 is supported */
2514 	if (svm->sev_es.ghcb->ghcb_usage) {
2515 		reason = GHCB_ERR_INVALID_USAGE;
2516 		goto vmgexit_err;
2517 	}
2518 
2519 	reason = GHCB_ERR_MISSING_INPUT;
2520 
2521 	if (!kvm_ghcb_sw_exit_code_is_valid(svm) ||
2522 	    !kvm_ghcb_sw_exit_info_1_is_valid(svm) ||
2523 	    !kvm_ghcb_sw_exit_info_2_is_valid(svm))
2524 		goto vmgexit_err;
2525 
2526 	switch (exit_code) {
2527 	case SVM_EXIT_READ_DR7:
2528 		break;
2529 	case SVM_EXIT_WRITE_DR7:
2530 		if (!kvm_ghcb_rax_is_valid(svm))
2531 			goto vmgexit_err;
2532 		break;
2533 	case SVM_EXIT_RDTSC:
2534 		break;
2535 	case SVM_EXIT_RDPMC:
2536 		if (!kvm_ghcb_rcx_is_valid(svm))
2537 			goto vmgexit_err;
2538 		break;
2539 	case SVM_EXIT_CPUID:
2540 		if (!kvm_ghcb_rax_is_valid(svm) ||
2541 		    !kvm_ghcb_rcx_is_valid(svm))
2542 			goto vmgexit_err;
2543 		if (vcpu->arch.regs[VCPU_REGS_RAX] == 0xd)
2544 			if (!kvm_ghcb_xcr0_is_valid(svm))
2545 				goto vmgexit_err;
2546 		break;
2547 	case SVM_EXIT_INVD:
2548 		break;
2549 	case SVM_EXIT_IOIO:
2550 		if (control->exit_info_1 & SVM_IOIO_STR_MASK) {
2551 			if (!kvm_ghcb_sw_scratch_is_valid(svm))
2552 				goto vmgexit_err;
2553 		} else {
2554 			if (!(control->exit_info_1 & SVM_IOIO_TYPE_MASK))
2555 				if (!kvm_ghcb_rax_is_valid(svm))
2556 					goto vmgexit_err;
2557 		}
2558 		break;
2559 	case SVM_EXIT_MSR:
2560 		if (!kvm_ghcb_rcx_is_valid(svm))
2561 			goto vmgexit_err;
2562 		if (control->exit_info_1) {
2563 			if (!kvm_ghcb_rax_is_valid(svm) ||
2564 			    !kvm_ghcb_rdx_is_valid(svm))
2565 				goto vmgexit_err;
2566 		}
2567 		break;
2568 	case SVM_EXIT_VMMCALL:
2569 		if (!kvm_ghcb_rax_is_valid(svm) ||
2570 		    !kvm_ghcb_cpl_is_valid(svm))
2571 			goto vmgexit_err;
2572 		break;
2573 	case SVM_EXIT_RDTSCP:
2574 		break;
2575 	case SVM_EXIT_WBINVD:
2576 		break;
2577 	case SVM_EXIT_MONITOR:
2578 		if (!kvm_ghcb_rax_is_valid(svm) ||
2579 		    !kvm_ghcb_rcx_is_valid(svm) ||
2580 		    !kvm_ghcb_rdx_is_valid(svm))
2581 			goto vmgexit_err;
2582 		break;
2583 	case SVM_EXIT_MWAIT:
2584 		if (!kvm_ghcb_rax_is_valid(svm) ||
2585 		    !kvm_ghcb_rcx_is_valid(svm))
2586 			goto vmgexit_err;
2587 		break;
2588 	case SVM_VMGEXIT_MMIO_READ:
2589 	case SVM_VMGEXIT_MMIO_WRITE:
2590 		if (!kvm_ghcb_sw_scratch_is_valid(svm))
2591 			goto vmgexit_err;
2592 		break;
2593 	case SVM_VMGEXIT_NMI_COMPLETE:
2594 	case SVM_VMGEXIT_AP_HLT_LOOP:
2595 	case SVM_VMGEXIT_AP_JUMP_TABLE:
2596 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
2597 		break;
2598 	default:
2599 		reason = GHCB_ERR_INVALID_EVENT;
2600 		goto vmgexit_err;
2601 	}
2602 
2603 	return 0;
2604 
2605 vmgexit_err:
2606 	if (reason == GHCB_ERR_INVALID_USAGE) {
2607 		vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
2608 			    svm->sev_es.ghcb->ghcb_usage);
2609 	} else if (reason == GHCB_ERR_INVALID_EVENT) {
2610 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is not valid\n",
2611 			    exit_code);
2612 	} else {
2613 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx input is not valid\n",
2614 			    exit_code);
2615 		dump_ghcb(svm);
2616 	}
2617 
2618 	ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
2619 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, reason);
2620 
2621 	/* Resume the guest to "return" the error code. */
2622 	return 1;
2623 }
2624 
2625 void sev_es_unmap_ghcb(struct vcpu_svm *svm)
2626 {
2627 	if (!svm->sev_es.ghcb)
2628 		return;
2629 
2630 	if (svm->sev_es.ghcb_sa_free) {
2631 		/*
2632 		 * The scratch area lives outside the GHCB, so there is a
2633 		 * buffer that, depending on the operation performed, may
2634 		 * need to be synced, then freed.
2635 		 */
2636 		if (svm->sev_es.ghcb_sa_sync) {
2637 			kvm_write_guest(svm->vcpu.kvm,
2638 					svm->sev_es.sw_scratch,
2639 					svm->sev_es.ghcb_sa,
2640 					svm->sev_es.ghcb_sa_len);
2641 			svm->sev_es.ghcb_sa_sync = false;
2642 		}
2643 
2644 		kvfree(svm->sev_es.ghcb_sa);
2645 		svm->sev_es.ghcb_sa = NULL;
2646 		svm->sev_es.ghcb_sa_free = false;
2647 	}
2648 
2649 	trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->sev_es.ghcb);
2650 
2651 	sev_es_sync_to_ghcb(svm);
2652 
2653 	kvm_vcpu_unmap(&svm->vcpu, &svm->sev_es.ghcb_map, true);
2654 	svm->sev_es.ghcb = NULL;
2655 }
2656 
2657 void pre_sev_run(struct vcpu_svm *svm, int cpu)
2658 {
2659 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
2660 	unsigned int asid = sev_get_asid(svm->vcpu.kvm);
2661 
2662 	/* Assign the asid allocated with this SEV guest */
2663 	svm->asid = asid;
2664 
2665 	/*
2666 	 * Flush guest TLB:
2667 	 *
2668 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
2669 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
2670 	 */
2671 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
2672 	    svm->vcpu.arch.last_vmentry_cpu == cpu)
2673 		return;
2674 
2675 	sd->sev_vmcbs[asid] = svm->vmcb;
2676 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
2677 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
2678 }
2679 
2680 #define GHCB_SCRATCH_AREA_LIMIT		(16ULL * PAGE_SIZE)
2681 static int setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len)
2682 {
2683 	struct vmcb_control_area *control = &svm->vmcb->control;
2684 	u64 ghcb_scratch_beg, ghcb_scratch_end;
2685 	u64 scratch_gpa_beg, scratch_gpa_end;
2686 	void *scratch_va;
2687 
2688 	scratch_gpa_beg = svm->sev_es.sw_scratch;
2689 	if (!scratch_gpa_beg) {
2690 		pr_err("vmgexit: scratch gpa not provided\n");
2691 		goto e_scratch;
2692 	}
2693 
2694 	scratch_gpa_end = scratch_gpa_beg + len;
2695 	if (scratch_gpa_end < scratch_gpa_beg) {
2696 		pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
2697 		       len, scratch_gpa_beg);
2698 		goto e_scratch;
2699 	}
2700 
2701 	if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
2702 		/* Scratch area begins within GHCB */
2703 		ghcb_scratch_beg = control->ghcb_gpa +
2704 				   offsetof(struct ghcb, shared_buffer);
2705 		ghcb_scratch_end = control->ghcb_gpa +
2706 				   offsetof(struct ghcb, reserved_0xff0);
2707 
2708 		/*
2709 		 * If the scratch area begins within the GHCB, it must be
2710 		 * completely contained in the GHCB shared buffer area.
2711 		 */
2712 		if (scratch_gpa_beg < ghcb_scratch_beg ||
2713 		    scratch_gpa_end > ghcb_scratch_end) {
2714 			pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
2715 			       scratch_gpa_beg, scratch_gpa_end);
2716 			goto e_scratch;
2717 		}
2718 
2719 		scratch_va = (void *)svm->sev_es.ghcb;
2720 		scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
2721 	} else {
2722 		/*
2723 		 * The guest memory must be read into a kernel buffer, so
2724 		 * limit the size
2725 		 */
2726 		if (len > GHCB_SCRATCH_AREA_LIMIT) {
2727 			pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
2728 			       len, GHCB_SCRATCH_AREA_LIMIT);
2729 			goto e_scratch;
2730 		}
2731 		scratch_va = kvzalloc(len, GFP_KERNEL_ACCOUNT);
2732 		if (!scratch_va)
2733 			return -ENOMEM;
2734 
2735 		if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) {
2736 			/* Unable to copy scratch area from guest */
2737 			pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
2738 
2739 			kvfree(scratch_va);
2740 			return -EFAULT;
2741 		}
2742 
2743 		/*
2744 		 * The scratch area is outside the GHCB. The operation will
2745 		 * dictate whether the buffer needs to be synced before running
2746 		 * the vCPU next time (i.e. a read was requested so the data
2747 		 * must be written back to the guest memory).
2748 		 */
2749 		svm->sev_es.ghcb_sa_sync = sync;
2750 		svm->sev_es.ghcb_sa_free = true;
2751 	}
2752 
2753 	svm->sev_es.ghcb_sa = scratch_va;
2754 	svm->sev_es.ghcb_sa_len = len;
2755 
2756 	return 0;
2757 
2758 e_scratch:
2759 	ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
2760 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_SCRATCH_AREA);
2761 
2762 	return 1;
2763 }
2764 
2765 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
2766 			      unsigned int pos)
2767 {
2768 	svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
2769 	svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
2770 }
2771 
2772 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
2773 {
2774 	return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
2775 }
2776 
2777 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
2778 {
2779 	svm->vmcb->control.ghcb_gpa = value;
2780 }
2781 
2782 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
2783 {
2784 	struct vmcb_control_area *control = &svm->vmcb->control;
2785 	struct kvm_vcpu *vcpu = &svm->vcpu;
2786 	u64 ghcb_info;
2787 	int ret = 1;
2788 
2789 	ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
2790 
2791 	trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
2792 					     control->ghcb_gpa);
2793 
2794 	switch (ghcb_info) {
2795 	case GHCB_MSR_SEV_INFO_REQ:
2796 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
2797 						    GHCB_VERSION_MIN,
2798 						    sev_enc_bit));
2799 		break;
2800 	case GHCB_MSR_CPUID_REQ: {
2801 		u64 cpuid_fn, cpuid_reg, cpuid_value;
2802 
2803 		cpuid_fn = get_ghcb_msr_bits(svm,
2804 					     GHCB_MSR_CPUID_FUNC_MASK,
2805 					     GHCB_MSR_CPUID_FUNC_POS);
2806 
2807 		/* Initialize the registers needed by the CPUID intercept */
2808 		vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
2809 		vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2810 
2811 		ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
2812 		if (!ret) {
2813 			/* Error, keep GHCB MSR value as-is */
2814 			break;
2815 		}
2816 
2817 		cpuid_reg = get_ghcb_msr_bits(svm,
2818 					      GHCB_MSR_CPUID_REG_MASK,
2819 					      GHCB_MSR_CPUID_REG_POS);
2820 		if (cpuid_reg == 0)
2821 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
2822 		else if (cpuid_reg == 1)
2823 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
2824 		else if (cpuid_reg == 2)
2825 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
2826 		else
2827 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
2828 
2829 		set_ghcb_msr_bits(svm, cpuid_value,
2830 				  GHCB_MSR_CPUID_VALUE_MASK,
2831 				  GHCB_MSR_CPUID_VALUE_POS);
2832 
2833 		set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
2834 				  GHCB_MSR_INFO_MASK,
2835 				  GHCB_MSR_INFO_POS);
2836 		break;
2837 	}
2838 	case GHCB_MSR_TERM_REQ: {
2839 		u64 reason_set, reason_code;
2840 
2841 		reason_set = get_ghcb_msr_bits(svm,
2842 					       GHCB_MSR_TERM_REASON_SET_MASK,
2843 					       GHCB_MSR_TERM_REASON_SET_POS);
2844 		reason_code = get_ghcb_msr_bits(svm,
2845 						GHCB_MSR_TERM_REASON_MASK,
2846 						GHCB_MSR_TERM_REASON_POS);
2847 		pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
2848 			reason_set, reason_code);
2849 
2850 		vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
2851 		vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
2852 		vcpu->run->system_event.ndata = 1;
2853 		vcpu->run->system_event.data[0] = control->ghcb_gpa;
2854 
2855 		return 0;
2856 	}
2857 	default:
2858 		/* Error, keep GHCB MSR value as-is */
2859 		break;
2860 	}
2861 
2862 	trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
2863 					    control->ghcb_gpa, ret);
2864 
2865 	return ret;
2866 }
2867 
2868 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
2869 {
2870 	struct vcpu_svm *svm = to_svm(vcpu);
2871 	struct vmcb_control_area *control = &svm->vmcb->control;
2872 	u64 ghcb_gpa, exit_code;
2873 	int ret;
2874 
2875 	/* Validate the GHCB */
2876 	ghcb_gpa = control->ghcb_gpa;
2877 	if (ghcb_gpa & GHCB_MSR_INFO_MASK)
2878 		return sev_handle_vmgexit_msr_protocol(svm);
2879 
2880 	if (!ghcb_gpa) {
2881 		vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n");
2882 
2883 		/* Without a GHCB, just return right back to the guest */
2884 		return 1;
2885 	}
2886 
2887 	if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->sev_es.ghcb_map)) {
2888 		/* Unable to map GHCB from guest */
2889 		vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
2890 			    ghcb_gpa);
2891 
2892 		/* Without a GHCB, just return right back to the guest */
2893 		return 1;
2894 	}
2895 
2896 	svm->sev_es.ghcb = svm->sev_es.ghcb_map.hva;
2897 
2898 	trace_kvm_vmgexit_enter(vcpu->vcpu_id, svm->sev_es.ghcb);
2899 
2900 	sev_es_sync_from_ghcb(svm);
2901 	ret = sev_es_validate_vmgexit(svm);
2902 	if (ret)
2903 		return ret;
2904 
2905 	ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 0);
2906 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 0);
2907 
2908 	exit_code = kvm_ghcb_get_sw_exit_code(control);
2909 	switch (exit_code) {
2910 	case SVM_VMGEXIT_MMIO_READ:
2911 		ret = setup_vmgexit_scratch(svm, true, control->exit_info_2);
2912 		if (ret)
2913 			break;
2914 
2915 		ret = kvm_sev_es_mmio_read(vcpu,
2916 					   control->exit_info_1,
2917 					   control->exit_info_2,
2918 					   svm->sev_es.ghcb_sa);
2919 		break;
2920 	case SVM_VMGEXIT_MMIO_WRITE:
2921 		ret = setup_vmgexit_scratch(svm, false, control->exit_info_2);
2922 		if (ret)
2923 			break;
2924 
2925 		ret = kvm_sev_es_mmio_write(vcpu,
2926 					    control->exit_info_1,
2927 					    control->exit_info_2,
2928 					    svm->sev_es.ghcb_sa);
2929 		break;
2930 	case SVM_VMGEXIT_NMI_COMPLETE:
2931 		++vcpu->stat.nmi_window_exits;
2932 		svm->nmi_masked = false;
2933 		kvm_make_request(KVM_REQ_EVENT, vcpu);
2934 		ret = 1;
2935 		break;
2936 	case SVM_VMGEXIT_AP_HLT_LOOP:
2937 		ret = kvm_emulate_ap_reset_hold(vcpu);
2938 		break;
2939 	case SVM_VMGEXIT_AP_JUMP_TABLE: {
2940 		struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
2941 
2942 		switch (control->exit_info_1) {
2943 		case 0:
2944 			/* Set AP jump table address */
2945 			sev->ap_jump_table = control->exit_info_2;
2946 			break;
2947 		case 1:
2948 			/* Get AP jump table address */
2949 			ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, sev->ap_jump_table);
2950 			break;
2951 		default:
2952 			pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
2953 			       control->exit_info_1);
2954 			ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
2955 			ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_INPUT);
2956 		}
2957 
2958 		ret = 1;
2959 		break;
2960 	}
2961 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
2962 		vcpu_unimpl(vcpu,
2963 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
2964 			    control->exit_info_1, control->exit_info_2);
2965 		ret = -EINVAL;
2966 		break;
2967 	default:
2968 		ret = svm_invoke_exit_handler(vcpu, exit_code);
2969 	}
2970 
2971 	return ret;
2972 }
2973 
2974 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
2975 {
2976 	int count;
2977 	int bytes;
2978 	int r;
2979 
2980 	if (svm->vmcb->control.exit_info_2 > INT_MAX)
2981 		return -EINVAL;
2982 
2983 	count = svm->vmcb->control.exit_info_2;
2984 	if (unlikely(check_mul_overflow(count, size, &bytes)))
2985 		return -EINVAL;
2986 
2987 	r = setup_vmgexit_scratch(svm, in, bytes);
2988 	if (r)
2989 		return r;
2990 
2991 	return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->sev_es.ghcb_sa,
2992 				    count, in);
2993 }
2994 
2995 static void sev_es_vcpu_after_set_cpuid(struct vcpu_svm *svm)
2996 {
2997 	struct kvm_vcpu *vcpu = &svm->vcpu;
2998 
2999 	if (boot_cpu_has(X86_FEATURE_V_TSC_AUX)) {
3000 		bool v_tsc_aux = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
3001 				 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
3002 
3003 		set_msr_interception(vcpu, svm->msrpm, MSR_TSC_AUX, v_tsc_aux, v_tsc_aux);
3004 	}
3005 
3006 	/*
3007 	 * For SEV-ES, accesses to MSR_IA32_XSS should not be intercepted if
3008 	 * the host/guest supports its use.
3009 	 *
3010 	 * guest_can_use() checks a number of requirements on the host/guest to
3011 	 * ensure that MSR_IA32_XSS is available, but it might report true even
3012 	 * if X86_FEATURE_XSAVES isn't configured in the guest to ensure host
3013 	 * MSR_IA32_XSS is always properly restored. For SEV-ES, it is better
3014 	 * to further check that the guest CPUID actually supports
3015 	 * X86_FEATURE_XSAVES so that accesses to MSR_IA32_XSS by misbehaved
3016 	 * guests will still get intercepted and caught in the normal
3017 	 * kvm_emulate_rdmsr()/kvm_emulated_wrmsr() paths.
3018 	 */
3019 	if (guest_can_use(vcpu, X86_FEATURE_XSAVES) &&
3020 	    guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
3021 		set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 1, 1);
3022 	else
3023 		set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 0, 0);
3024 }
3025 
3026 void sev_vcpu_after_set_cpuid(struct vcpu_svm *svm)
3027 {
3028 	struct kvm_vcpu *vcpu = &svm->vcpu;
3029 	struct kvm_cpuid_entry2 *best;
3030 
3031 	/* For sev guests, the memory encryption bit is not reserved in CR3.  */
3032 	best = kvm_find_cpuid_entry(vcpu, 0x8000001F);
3033 	if (best)
3034 		vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
3035 
3036 	if (sev_es_guest(svm->vcpu.kvm))
3037 		sev_es_vcpu_after_set_cpuid(svm);
3038 }
3039 
3040 static void sev_es_init_vmcb(struct vcpu_svm *svm)
3041 {
3042 	struct vmcb *vmcb = svm->vmcb01.ptr;
3043 	struct kvm_vcpu *vcpu = &svm->vcpu;
3044 
3045 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE;
3046 
3047 	/*
3048 	 * An SEV-ES guest requires a VMSA area that is a separate from the
3049 	 * VMCB page. Do not include the encryption mask on the VMSA physical
3050 	 * address since hardware will access it using the guest key.  Note,
3051 	 * the VMSA will be NULL if this vCPU is the destination for intrahost
3052 	 * migration, and will be copied later.
3053 	 */
3054 	if (svm->sev_es.vmsa)
3055 		svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa);
3056 
3057 	/* Can't intercept CR register access, HV can't modify CR registers */
3058 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
3059 	svm_clr_intercept(svm, INTERCEPT_CR4_READ);
3060 	svm_clr_intercept(svm, INTERCEPT_CR8_READ);
3061 	svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
3062 	svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
3063 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3064 
3065 	svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
3066 
3067 	/* Track EFER/CR register changes */
3068 	svm_set_intercept(svm, TRAP_EFER_WRITE);
3069 	svm_set_intercept(svm, TRAP_CR0_WRITE);
3070 	svm_set_intercept(svm, TRAP_CR4_WRITE);
3071 	svm_set_intercept(svm, TRAP_CR8_WRITE);
3072 
3073 	vmcb->control.intercepts[INTERCEPT_DR] = 0;
3074 	if (!sev_es_debug_swap_enabled) {
3075 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
3076 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
3077 		recalc_intercepts(svm);
3078 	} else {
3079 		/*
3080 		 * Disable #DB intercept iff DebugSwap is enabled.  KVM doesn't
3081 		 * allow debugging SEV-ES guests, and enables DebugSwap iff
3082 		 * NO_NESTED_DATA_BP is supported, so there's no reason to
3083 		 * intercept #DB when DebugSwap is enabled.  For simplicity
3084 		 * with respect to guest debug, intercept #DB for other VMs
3085 		 * even if NO_NESTED_DATA_BP is supported, i.e. even if the
3086 		 * guest can't DoS the CPU with infinite #DB vectoring.
3087 		 */
3088 		clr_exception_intercept(svm, DB_VECTOR);
3089 	}
3090 
3091 	/* Can't intercept XSETBV, HV can't modify XCR0 directly */
3092 	svm_clr_intercept(svm, INTERCEPT_XSETBV);
3093 
3094 	/* Clear intercepts on selected MSRs */
3095 	set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1);
3096 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1);
3097 }
3098 
3099 void sev_init_vmcb(struct vcpu_svm *svm)
3100 {
3101 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
3102 	clr_exception_intercept(svm, UD_VECTOR);
3103 
3104 	/*
3105 	 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as
3106 	 * KVM can't decrypt guest memory to decode the faulting instruction.
3107 	 */
3108 	clr_exception_intercept(svm, GP_VECTOR);
3109 
3110 	if (sev_es_guest(svm->vcpu.kvm))
3111 		sev_es_init_vmcb(svm);
3112 }
3113 
3114 void sev_es_vcpu_reset(struct vcpu_svm *svm)
3115 {
3116 	/*
3117 	 * Set the GHCB MSR value as per the GHCB specification when emulating
3118 	 * vCPU RESET for an SEV-ES guest.
3119 	 */
3120 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
3121 					    GHCB_VERSION_MIN,
3122 					    sev_enc_bit));
3123 }
3124 
3125 void sev_es_prepare_switch_to_guest(struct sev_es_save_area *hostsa)
3126 {
3127 	/*
3128 	 * All host state for SEV-ES guests is categorized into three swap types
3129 	 * based on how it is handled by hardware during a world switch:
3130 	 *
3131 	 * A: VMRUN:   Host state saved in host save area
3132 	 *    VMEXIT:  Host state loaded from host save area
3133 	 *
3134 	 * B: VMRUN:   Host state _NOT_ saved in host save area
3135 	 *    VMEXIT:  Host state loaded from host save area
3136 	 *
3137 	 * C: VMRUN:   Host state _NOT_ saved in host save area
3138 	 *    VMEXIT:  Host state initialized to default(reset) values
3139 	 *
3140 	 * Manually save type-B state, i.e. state that is loaded by VMEXIT but
3141 	 * isn't saved by VMRUN, that isn't already saved by VMSAVE (performed
3142 	 * by common SVM code).
3143 	 */
3144 	hostsa->xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
3145 	hostsa->pkru = read_pkru();
3146 	hostsa->xss = host_xss;
3147 
3148 	/*
3149 	 * If DebugSwap is enabled, debug registers are loaded but NOT saved by
3150 	 * the CPU (Type-B). If DebugSwap is disabled/unsupported, the CPU both
3151 	 * saves and loads debug registers (Type-A).
3152 	 */
3153 	if (sev_es_debug_swap_enabled) {
3154 		hostsa->dr0 = native_get_debugreg(0);
3155 		hostsa->dr1 = native_get_debugreg(1);
3156 		hostsa->dr2 = native_get_debugreg(2);
3157 		hostsa->dr3 = native_get_debugreg(3);
3158 		hostsa->dr0_addr_mask = amd_get_dr_addr_mask(0);
3159 		hostsa->dr1_addr_mask = amd_get_dr_addr_mask(1);
3160 		hostsa->dr2_addr_mask = amd_get_dr_addr_mask(2);
3161 		hostsa->dr3_addr_mask = amd_get_dr_addr_mask(3);
3162 	}
3163 }
3164 
3165 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
3166 {
3167 	struct vcpu_svm *svm = to_svm(vcpu);
3168 
3169 	/* First SIPI: Use the values as initially set by the VMM */
3170 	if (!svm->sev_es.received_first_sipi) {
3171 		svm->sev_es.received_first_sipi = true;
3172 		return;
3173 	}
3174 
3175 	/*
3176 	 * Subsequent SIPI: Return from an AP Reset Hold VMGEXIT, where
3177 	 * the guest will set the CS and RIP. Set SW_EXIT_INFO_2 to a
3178 	 * non-zero value.
3179 	 */
3180 	if (!svm->sev_es.ghcb)
3181 		return;
3182 
3183 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 1);
3184 }
3185