xref: /openbmc/linux/arch/x86/kvm/svm/sev.c (revision 2c733bb7)
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 	return 0;
668 }
669 
670 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
671 {
672 	struct kvm_vcpu *vcpu;
673 	unsigned long i;
674 	int ret;
675 
676 	if (!sev_es_guest(kvm))
677 		return -ENOTTY;
678 
679 	kvm_for_each_vcpu(i, vcpu, kvm) {
680 		ret = mutex_lock_killable(&vcpu->mutex);
681 		if (ret)
682 			return ret;
683 
684 		ret = __sev_launch_update_vmsa(kvm, vcpu, &argp->error);
685 
686 		mutex_unlock(&vcpu->mutex);
687 		if (ret)
688 			return ret;
689 	}
690 
691 	return 0;
692 }
693 
694 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
695 {
696 	void __user *measure = (void __user *)(uintptr_t)argp->data;
697 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
698 	struct sev_data_launch_measure data;
699 	struct kvm_sev_launch_measure params;
700 	void __user *p = NULL;
701 	void *blob = NULL;
702 	int ret;
703 
704 	if (!sev_guest(kvm))
705 		return -ENOTTY;
706 
707 	if (copy_from_user(&params, measure, sizeof(params)))
708 		return -EFAULT;
709 
710 	memset(&data, 0, sizeof(data));
711 
712 	/* User wants to query the blob length */
713 	if (!params.len)
714 		goto cmd;
715 
716 	p = (void __user *)(uintptr_t)params.uaddr;
717 	if (p) {
718 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
719 			return -EINVAL;
720 
721 		blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
722 		if (!blob)
723 			return -ENOMEM;
724 
725 		data.address = __psp_pa(blob);
726 		data.len = params.len;
727 	}
728 
729 cmd:
730 	data.handle = sev->handle;
731 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, &data, &argp->error);
732 
733 	/*
734 	 * If we query the session length, FW responded with expected data.
735 	 */
736 	if (!params.len)
737 		goto done;
738 
739 	if (ret)
740 		goto e_free_blob;
741 
742 	if (blob) {
743 		if (copy_to_user(p, blob, params.len))
744 			ret = -EFAULT;
745 	}
746 
747 done:
748 	params.len = data.len;
749 	if (copy_to_user(measure, &params, sizeof(params)))
750 		ret = -EFAULT;
751 e_free_blob:
752 	kfree(blob);
753 	return ret;
754 }
755 
756 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
757 {
758 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
759 	struct sev_data_launch_finish data;
760 
761 	if (!sev_guest(kvm))
762 		return -ENOTTY;
763 
764 	data.handle = sev->handle;
765 	return sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, &data, &argp->error);
766 }
767 
768 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
769 {
770 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
771 	struct kvm_sev_guest_status params;
772 	struct sev_data_guest_status data;
773 	int ret;
774 
775 	if (!sev_guest(kvm))
776 		return -ENOTTY;
777 
778 	memset(&data, 0, sizeof(data));
779 
780 	data.handle = sev->handle;
781 	ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, &data, &argp->error);
782 	if (ret)
783 		return ret;
784 
785 	params.policy = data.policy;
786 	params.state = data.state;
787 	params.handle = data.handle;
788 
789 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
790 		ret = -EFAULT;
791 
792 	return ret;
793 }
794 
795 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
796 			       unsigned long dst, int size,
797 			       int *error, bool enc)
798 {
799 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
800 	struct sev_data_dbg data;
801 
802 	data.reserved = 0;
803 	data.handle = sev->handle;
804 	data.dst_addr = dst;
805 	data.src_addr = src;
806 	data.len = size;
807 
808 	return sev_issue_cmd(kvm,
809 			     enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
810 			     &data, error);
811 }
812 
813 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
814 			     unsigned long dst_paddr, int sz, int *err)
815 {
816 	int offset;
817 
818 	/*
819 	 * Its safe to read more than we are asked, caller should ensure that
820 	 * destination has enough space.
821 	 */
822 	offset = src_paddr & 15;
823 	src_paddr = round_down(src_paddr, 16);
824 	sz = round_up(sz + offset, 16);
825 
826 	return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
827 }
828 
829 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
830 				  void __user *dst_uaddr,
831 				  unsigned long dst_paddr,
832 				  int size, int *err)
833 {
834 	struct page *tpage = NULL;
835 	int ret, offset;
836 
837 	/* if inputs are not 16-byte then use intermediate buffer */
838 	if (!IS_ALIGNED(dst_paddr, 16) ||
839 	    !IS_ALIGNED(paddr,     16) ||
840 	    !IS_ALIGNED(size,      16)) {
841 		tpage = (void *)alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
842 		if (!tpage)
843 			return -ENOMEM;
844 
845 		dst_paddr = __sme_page_pa(tpage);
846 	}
847 
848 	ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
849 	if (ret)
850 		goto e_free;
851 
852 	if (tpage) {
853 		offset = paddr & 15;
854 		if (copy_to_user(dst_uaddr, page_address(tpage) + offset, size))
855 			ret = -EFAULT;
856 	}
857 
858 e_free:
859 	if (tpage)
860 		__free_page(tpage);
861 
862 	return ret;
863 }
864 
865 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
866 				  void __user *vaddr,
867 				  unsigned long dst_paddr,
868 				  void __user *dst_vaddr,
869 				  int size, int *error)
870 {
871 	struct page *src_tpage = NULL;
872 	struct page *dst_tpage = NULL;
873 	int ret, len = size;
874 
875 	/* If source buffer is not aligned then use an intermediate buffer */
876 	if (!IS_ALIGNED((unsigned long)vaddr, 16)) {
877 		src_tpage = alloc_page(GFP_KERNEL_ACCOUNT);
878 		if (!src_tpage)
879 			return -ENOMEM;
880 
881 		if (copy_from_user(page_address(src_tpage), vaddr, size)) {
882 			__free_page(src_tpage);
883 			return -EFAULT;
884 		}
885 
886 		paddr = __sme_page_pa(src_tpage);
887 	}
888 
889 	/*
890 	 *  If destination buffer or length is not aligned then do read-modify-write:
891 	 *   - decrypt destination in an intermediate buffer
892 	 *   - copy the source buffer in an intermediate buffer
893 	 *   - use the intermediate buffer as source buffer
894 	 */
895 	if (!IS_ALIGNED((unsigned long)dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
896 		int dst_offset;
897 
898 		dst_tpage = alloc_page(GFP_KERNEL_ACCOUNT);
899 		if (!dst_tpage) {
900 			ret = -ENOMEM;
901 			goto e_free;
902 		}
903 
904 		ret = __sev_dbg_decrypt(kvm, dst_paddr,
905 					__sme_page_pa(dst_tpage), size, error);
906 		if (ret)
907 			goto e_free;
908 
909 		/*
910 		 *  If source is kernel buffer then use memcpy() otherwise
911 		 *  copy_from_user().
912 		 */
913 		dst_offset = dst_paddr & 15;
914 
915 		if (src_tpage)
916 			memcpy(page_address(dst_tpage) + dst_offset,
917 			       page_address(src_tpage), size);
918 		else {
919 			if (copy_from_user(page_address(dst_tpage) + dst_offset,
920 					   vaddr, size)) {
921 				ret = -EFAULT;
922 				goto e_free;
923 			}
924 		}
925 
926 		paddr = __sme_page_pa(dst_tpage);
927 		dst_paddr = round_down(dst_paddr, 16);
928 		len = round_up(size, 16);
929 	}
930 
931 	ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
932 
933 e_free:
934 	if (src_tpage)
935 		__free_page(src_tpage);
936 	if (dst_tpage)
937 		__free_page(dst_tpage);
938 	return ret;
939 }
940 
941 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
942 {
943 	unsigned long vaddr, vaddr_end, next_vaddr;
944 	unsigned long dst_vaddr;
945 	struct page **src_p, **dst_p;
946 	struct kvm_sev_dbg debug;
947 	unsigned long n;
948 	unsigned int size;
949 	int ret;
950 
951 	if (!sev_guest(kvm))
952 		return -ENOTTY;
953 
954 	if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
955 		return -EFAULT;
956 
957 	if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
958 		return -EINVAL;
959 	if (!debug.dst_uaddr)
960 		return -EINVAL;
961 
962 	vaddr = debug.src_uaddr;
963 	size = debug.len;
964 	vaddr_end = vaddr + size;
965 	dst_vaddr = debug.dst_uaddr;
966 
967 	for (; vaddr < vaddr_end; vaddr = next_vaddr) {
968 		int len, s_off, d_off;
969 
970 		/* lock userspace source and destination page */
971 		src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
972 		if (IS_ERR(src_p))
973 			return PTR_ERR(src_p);
974 
975 		dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
976 		if (IS_ERR(dst_p)) {
977 			sev_unpin_memory(kvm, src_p, n);
978 			return PTR_ERR(dst_p);
979 		}
980 
981 		/*
982 		 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify
983 		 * the pages; flush the destination too so that future accesses do not
984 		 * see stale data.
985 		 */
986 		sev_clflush_pages(src_p, 1);
987 		sev_clflush_pages(dst_p, 1);
988 
989 		/*
990 		 * Since user buffer may not be page aligned, calculate the
991 		 * offset within the page.
992 		 */
993 		s_off = vaddr & ~PAGE_MASK;
994 		d_off = dst_vaddr & ~PAGE_MASK;
995 		len = min_t(size_t, (PAGE_SIZE - s_off), size);
996 
997 		if (dec)
998 			ret = __sev_dbg_decrypt_user(kvm,
999 						     __sme_page_pa(src_p[0]) + s_off,
1000 						     (void __user *)dst_vaddr,
1001 						     __sme_page_pa(dst_p[0]) + d_off,
1002 						     len, &argp->error);
1003 		else
1004 			ret = __sev_dbg_encrypt_user(kvm,
1005 						     __sme_page_pa(src_p[0]) + s_off,
1006 						     (void __user *)vaddr,
1007 						     __sme_page_pa(dst_p[0]) + d_off,
1008 						     (void __user *)dst_vaddr,
1009 						     len, &argp->error);
1010 
1011 		sev_unpin_memory(kvm, src_p, n);
1012 		sev_unpin_memory(kvm, dst_p, n);
1013 
1014 		if (ret)
1015 			goto err;
1016 
1017 		next_vaddr = vaddr + len;
1018 		dst_vaddr = dst_vaddr + len;
1019 		size -= len;
1020 	}
1021 err:
1022 	return ret;
1023 }
1024 
1025 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
1026 {
1027 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1028 	struct sev_data_launch_secret data;
1029 	struct kvm_sev_launch_secret params;
1030 	struct page **pages;
1031 	void *blob, *hdr;
1032 	unsigned long n, i;
1033 	int ret, offset;
1034 
1035 	if (!sev_guest(kvm))
1036 		return -ENOTTY;
1037 
1038 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
1039 		return -EFAULT;
1040 
1041 	pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
1042 	if (IS_ERR(pages))
1043 		return PTR_ERR(pages);
1044 
1045 	/*
1046 	 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in
1047 	 * place; the cache may contain the data that was written unencrypted.
1048 	 */
1049 	sev_clflush_pages(pages, n);
1050 
1051 	/*
1052 	 * The secret must be copied into contiguous memory region, lets verify
1053 	 * that userspace memory pages are contiguous before we issue command.
1054 	 */
1055 	if (get_num_contig_pages(0, pages, n) != n) {
1056 		ret = -EINVAL;
1057 		goto e_unpin_memory;
1058 	}
1059 
1060 	memset(&data, 0, sizeof(data));
1061 
1062 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1063 	data.guest_address = __sme_page_pa(pages[0]) + offset;
1064 	data.guest_len = params.guest_len;
1065 
1066 	blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1067 	if (IS_ERR(blob)) {
1068 		ret = PTR_ERR(blob);
1069 		goto e_unpin_memory;
1070 	}
1071 
1072 	data.trans_address = __psp_pa(blob);
1073 	data.trans_len = params.trans_len;
1074 
1075 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1076 	if (IS_ERR(hdr)) {
1077 		ret = PTR_ERR(hdr);
1078 		goto e_free_blob;
1079 	}
1080 	data.hdr_address = __psp_pa(hdr);
1081 	data.hdr_len = params.hdr_len;
1082 
1083 	data.handle = sev->handle;
1084 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, &data, &argp->error);
1085 
1086 	kfree(hdr);
1087 
1088 e_free_blob:
1089 	kfree(blob);
1090 e_unpin_memory:
1091 	/* content of memory is updated, mark pages dirty */
1092 	for (i = 0; i < n; i++) {
1093 		set_page_dirty_lock(pages[i]);
1094 		mark_page_accessed(pages[i]);
1095 	}
1096 	sev_unpin_memory(kvm, pages, n);
1097 	return ret;
1098 }
1099 
1100 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp)
1101 {
1102 	void __user *report = (void __user *)(uintptr_t)argp->data;
1103 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1104 	struct sev_data_attestation_report data;
1105 	struct kvm_sev_attestation_report params;
1106 	void __user *p;
1107 	void *blob = NULL;
1108 	int ret;
1109 
1110 	if (!sev_guest(kvm))
1111 		return -ENOTTY;
1112 
1113 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
1114 		return -EFAULT;
1115 
1116 	memset(&data, 0, sizeof(data));
1117 
1118 	/* User wants to query the blob length */
1119 	if (!params.len)
1120 		goto cmd;
1121 
1122 	p = (void __user *)(uintptr_t)params.uaddr;
1123 	if (p) {
1124 		if (params.len > SEV_FW_BLOB_MAX_SIZE)
1125 			return -EINVAL;
1126 
1127 		blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
1128 		if (!blob)
1129 			return -ENOMEM;
1130 
1131 		data.address = __psp_pa(blob);
1132 		data.len = params.len;
1133 		memcpy(data.mnonce, params.mnonce, sizeof(params.mnonce));
1134 	}
1135 cmd:
1136 	data.handle = sev->handle;
1137 	ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, &data, &argp->error);
1138 	/*
1139 	 * If we query the session length, FW responded with expected data.
1140 	 */
1141 	if (!params.len)
1142 		goto done;
1143 
1144 	if (ret)
1145 		goto e_free_blob;
1146 
1147 	if (blob) {
1148 		if (copy_to_user(p, blob, params.len))
1149 			ret = -EFAULT;
1150 	}
1151 
1152 done:
1153 	params.len = data.len;
1154 	if (copy_to_user(report, &params, sizeof(params)))
1155 		ret = -EFAULT;
1156 e_free_blob:
1157 	kfree(blob);
1158 	return ret;
1159 }
1160 
1161 /* Userspace wants to query session length. */
1162 static int
1163 __sev_send_start_query_session_length(struct kvm *kvm, struct kvm_sev_cmd *argp,
1164 				      struct kvm_sev_send_start *params)
1165 {
1166 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1167 	struct sev_data_send_start data;
1168 	int ret;
1169 
1170 	memset(&data, 0, sizeof(data));
1171 	data.handle = sev->handle;
1172 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1173 
1174 	params->session_len = data.session_len;
1175 	if (copy_to_user((void __user *)(uintptr_t)argp->data, params,
1176 				sizeof(struct kvm_sev_send_start)))
1177 		ret = -EFAULT;
1178 
1179 	return ret;
1180 }
1181 
1182 static int sev_send_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1183 {
1184 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1185 	struct sev_data_send_start data;
1186 	struct kvm_sev_send_start params;
1187 	void *amd_certs, *session_data;
1188 	void *pdh_cert, *plat_certs;
1189 	int ret;
1190 
1191 	if (!sev_guest(kvm))
1192 		return -ENOTTY;
1193 
1194 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1195 				sizeof(struct kvm_sev_send_start)))
1196 		return -EFAULT;
1197 
1198 	/* if session_len is zero, userspace wants to query the session length */
1199 	if (!params.session_len)
1200 		return __sev_send_start_query_session_length(kvm, argp,
1201 				&params);
1202 
1203 	/* some sanity checks */
1204 	if (!params.pdh_cert_uaddr || !params.pdh_cert_len ||
1205 	    !params.session_uaddr || params.session_len > SEV_FW_BLOB_MAX_SIZE)
1206 		return -EINVAL;
1207 
1208 	/* allocate the memory to hold the session data blob */
1209 	session_data = kzalloc(params.session_len, GFP_KERNEL_ACCOUNT);
1210 	if (!session_data)
1211 		return -ENOMEM;
1212 
1213 	/* copy the certificate blobs from userspace */
1214 	pdh_cert = psp_copy_user_blob(params.pdh_cert_uaddr,
1215 				params.pdh_cert_len);
1216 	if (IS_ERR(pdh_cert)) {
1217 		ret = PTR_ERR(pdh_cert);
1218 		goto e_free_session;
1219 	}
1220 
1221 	plat_certs = psp_copy_user_blob(params.plat_certs_uaddr,
1222 				params.plat_certs_len);
1223 	if (IS_ERR(plat_certs)) {
1224 		ret = PTR_ERR(plat_certs);
1225 		goto e_free_pdh;
1226 	}
1227 
1228 	amd_certs = psp_copy_user_blob(params.amd_certs_uaddr,
1229 				params.amd_certs_len);
1230 	if (IS_ERR(amd_certs)) {
1231 		ret = PTR_ERR(amd_certs);
1232 		goto e_free_plat_cert;
1233 	}
1234 
1235 	/* populate the FW SEND_START field with system physical address */
1236 	memset(&data, 0, sizeof(data));
1237 	data.pdh_cert_address = __psp_pa(pdh_cert);
1238 	data.pdh_cert_len = params.pdh_cert_len;
1239 	data.plat_certs_address = __psp_pa(plat_certs);
1240 	data.plat_certs_len = params.plat_certs_len;
1241 	data.amd_certs_address = __psp_pa(amd_certs);
1242 	data.amd_certs_len = params.amd_certs_len;
1243 	data.session_address = __psp_pa(session_data);
1244 	data.session_len = params.session_len;
1245 	data.handle = sev->handle;
1246 
1247 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1248 
1249 	if (!ret && copy_to_user((void __user *)(uintptr_t)params.session_uaddr,
1250 			session_data, params.session_len)) {
1251 		ret = -EFAULT;
1252 		goto e_free_amd_cert;
1253 	}
1254 
1255 	params.policy = data.policy;
1256 	params.session_len = data.session_len;
1257 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params,
1258 				sizeof(struct kvm_sev_send_start)))
1259 		ret = -EFAULT;
1260 
1261 e_free_amd_cert:
1262 	kfree(amd_certs);
1263 e_free_plat_cert:
1264 	kfree(plat_certs);
1265 e_free_pdh:
1266 	kfree(pdh_cert);
1267 e_free_session:
1268 	kfree(session_data);
1269 	return ret;
1270 }
1271 
1272 /* Userspace wants to query either header or trans length. */
1273 static int
1274 __sev_send_update_data_query_lengths(struct kvm *kvm, struct kvm_sev_cmd *argp,
1275 				     struct kvm_sev_send_update_data *params)
1276 {
1277 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1278 	struct sev_data_send_update_data data;
1279 	int ret;
1280 
1281 	memset(&data, 0, sizeof(data));
1282 	data.handle = sev->handle;
1283 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1284 
1285 	params->hdr_len = data.hdr_len;
1286 	params->trans_len = data.trans_len;
1287 
1288 	if (copy_to_user((void __user *)(uintptr_t)argp->data, params,
1289 			 sizeof(struct kvm_sev_send_update_data)))
1290 		ret = -EFAULT;
1291 
1292 	return ret;
1293 }
1294 
1295 static int sev_send_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1296 {
1297 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1298 	struct sev_data_send_update_data data;
1299 	struct kvm_sev_send_update_data params;
1300 	void *hdr, *trans_data;
1301 	struct page **guest_page;
1302 	unsigned long n;
1303 	int ret, offset;
1304 
1305 	if (!sev_guest(kvm))
1306 		return -ENOTTY;
1307 
1308 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1309 			sizeof(struct kvm_sev_send_update_data)))
1310 		return -EFAULT;
1311 
1312 	/* userspace wants to query either header or trans length */
1313 	if (!params.trans_len || !params.hdr_len)
1314 		return __sev_send_update_data_query_lengths(kvm, argp, &params);
1315 
1316 	if (!params.trans_uaddr || !params.guest_uaddr ||
1317 	    !params.guest_len || !params.hdr_uaddr)
1318 		return -EINVAL;
1319 
1320 	/* Check if we are crossing the page boundary */
1321 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1322 	if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1323 		return -EINVAL;
1324 
1325 	/* Pin guest memory */
1326 	guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1327 				    PAGE_SIZE, &n, 0);
1328 	if (IS_ERR(guest_page))
1329 		return PTR_ERR(guest_page);
1330 
1331 	/* allocate memory for header and transport buffer */
1332 	ret = -ENOMEM;
1333 	hdr = kzalloc(params.hdr_len, GFP_KERNEL_ACCOUNT);
1334 	if (!hdr)
1335 		goto e_unpin;
1336 
1337 	trans_data = kzalloc(params.trans_len, GFP_KERNEL_ACCOUNT);
1338 	if (!trans_data)
1339 		goto e_free_hdr;
1340 
1341 	memset(&data, 0, sizeof(data));
1342 	data.hdr_address = __psp_pa(hdr);
1343 	data.hdr_len = params.hdr_len;
1344 	data.trans_address = __psp_pa(trans_data);
1345 	data.trans_len = params.trans_len;
1346 
1347 	/* The SEND_UPDATE_DATA command requires C-bit to be always set. */
1348 	data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1349 	data.guest_address |= sev_me_mask;
1350 	data.guest_len = params.guest_len;
1351 	data.handle = sev->handle;
1352 
1353 	ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1354 
1355 	if (ret)
1356 		goto e_free_trans_data;
1357 
1358 	/* copy transport buffer to user space */
1359 	if (copy_to_user((void __user *)(uintptr_t)params.trans_uaddr,
1360 			 trans_data, params.trans_len)) {
1361 		ret = -EFAULT;
1362 		goto e_free_trans_data;
1363 	}
1364 
1365 	/* Copy packet header to userspace. */
1366 	if (copy_to_user((void __user *)(uintptr_t)params.hdr_uaddr, hdr,
1367 			 params.hdr_len))
1368 		ret = -EFAULT;
1369 
1370 e_free_trans_data:
1371 	kfree(trans_data);
1372 e_free_hdr:
1373 	kfree(hdr);
1374 e_unpin:
1375 	sev_unpin_memory(kvm, guest_page, n);
1376 
1377 	return ret;
1378 }
1379 
1380 static int sev_send_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1381 {
1382 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1383 	struct sev_data_send_finish data;
1384 
1385 	if (!sev_guest(kvm))
1386 		return -ENOTTY;
1387 
1388 	data.handle = sev->handle;
1389 	return sev_issue_cmd(kvm, SEV_CMD_SEND_FINISH, &data, &argp->error);
1390 }
1391 
1392 static int sev_send_cancel(struct kvm *kvm, struct kvm_sev_cmd *argp)
1393 {
1394 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1395 	struct sev_data_send_cancel data;
1396 
1397 	if (!sev_guest(kvm))
1398 		return -ENOTTY;
1399 
1400 	data.handle = sev->handle;
1401 	return sev_issue_cmd(kvm, SEV_CMD_SEND_CANCEL, &data, &argp->error);
1402 }
1403 
1404 static int sev_receive_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1405 {
1406 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1407 	struct sev_data_receive_start start;
1408 	struct kvm_sev_receive_start params;
1409 	int *error = &argp->error;
1410 	void *session_data;
1411 	void *pdh_data;
1412 	int ret;
1413 
1414 	if (!sev_guest(kvm))
1415 		return -ENOTTY;
1416 
1417 	/* Get parameter from the userspace */
1418 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1419 			sizeof(struct kvm_sev_receive_start)))
1420 		return -EFAULT;
1421 
1422 	/* some sanity checks */
1423 	if (!params.pdh_uaddr || !params.pdh_len ||
1424 	    !params.session_uaddr || !params.session_len)
1425 		return -EINVAL;
1426 
1427 	pdh_data = psp_copy_user_blob(params.pdh_uaddr, params.pdh_len);
1428 	if (IS_ERR(pdh_data))
1429 		return PTR_ERR(pdh_data);
1430 
1431 	session_data = psp_copy_user_blob(params.session_uaddr,
1432 			params.session_len);
1433 	if (IS_ERR(session_data)) {
1434 		ret = PTR_ERR(session_data);
1435 		goto e_free_pdh;
1436 	}
1437 
1438 	memset(&start, 0, sizeof(start));
1439 	start.handle = params.handle;
1440 	start.policy = params.policy;
1441 	start.pdh_cert_address = __psp_pa(pdh_data);
1442 	start.pdh_cert_len = params.pdh_len;
1443 	start.session_address = __psp_pa(session_data);
1444 	start.session_len = params.session_len;
1445 
1446 	/* create memory encryption context */
1447 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_RECEIVE_START, &start,
1448 				error);
1449 	if (ret)
1450 		goto e_free_session;
1451 
1452 	/* Bind ASID to this guest */
1453 	ret = sev_bind_asid(kvm, start.handle, error);
1454 	if (ret) {
1455 		sev_decommission(start.handle);
1456 		goto e_free_session;
1457 	}
1458 
1459 	params.handle = start.handle;
1460 	if (copy_to_user((void __user *)(uintptr_t)argp->data,
1461 			 &params, sizeof(struct kvm_sev_receive_start))) {
1462 		ret = -EFAULT;
1463 		sev_unbind_asid(kvm, start.handle);
1464 		goto e_free_session;
1465 	}
1466 
1467     	sev->handle = start.handle;
1468 	sev->fd = argp->sev_fd;
1469 
1470 e_free_session:
1471 	kfree(session_data);
1472 e_free_pdh:
1473 	kfree(pdh_data);
1474 
1475 	return ret;
1476 }
1477 
1478 static int sev_receive_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1479 {
1480 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1481 	struct kvm_sev_receive_update_data params;
1482 	struct sev_data_receive_update_data data;
1483 	void *hdr = NULL, *trans = NULL;
1484 	struct page **guest_page;
1485 	unsigned long n;
1486 	int ret, offset;
1487 
1488 	if (!sev_guest(kvm))
1489 		return -EINVAL;
1490 
1491 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data,
1492 			sizeof(struct kvm_sev_receive_update_data)))
1493 		return -EFAULT;
1494 
1495 	if (!params.hdr_uaddr || !params.hdr_len ||
1496 	    !params.guest_uaddr || !params.guest_len ||
1497 	    !params.trans_uaddr || !params.trans_len)
1498 		return -EINVAL;
1499 
1500 	/* Check if we are crossing the page boundary */
1501 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1502 	if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1503 		return -EINVAL;
1504 
1505 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1506 	if (IS_ERR(hdr))
1507 		return PTR_ERR(hdr);
1508 
1509 	trans = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1510 	if (IS_ERR(trans)) {
1511 		ret = PTR_ERR(trans);
1512 		goto e_free_hdr;
1513 	}
1514 
1515 	memset(&data, 0, sizeof(data));
1516 	data.hdr_address = __psp_pa(hdr);
1517 	data.hdr_len = params.hdr_len;
1518 	data.trans_address = __psp_pa(trans);
1519 	data.trans_len = params.trans_len;
1520 
1521 	/* Pin guest memory */
1522 	guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1523 				    PAGE_SIZE, &n, 1);
1524 	if (IS_ERR(guest_page)) {
1525 		ret = PTR_ERR(guest_page);
1526 		goto e_free_trans;
1527 	}
1528 
1529 	/*
1530 	 * Flush (on non-coherent CPUs) before RECEIVE_UPDATE_DATA, the PSP
1531 	 * encrypts the written data with the guest's key, and the cache may
1532 	 * contain dirty, unencrypted data.
1533 	 */
1534 	sev_clflush_pages(guest_page, n);
1535 
1536 	/* The RECEIVE_UPDATE_DATA command requires C-bit to be always set. */
1537 	data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1538 	data.guest_address |= sev_me_mask;
1539 	data.guest_len = params.guest_len;
1540 	data.handle = sev->handle;
1541 
1542 	ret = sev_issue_cmd(kvm, SEV_CMD_RECEIVE_UPDATE_DATA, &data,
1543 				&argp->error);
1544 
1545 	sev_unpin_memory(kvm, guest_page, n);
1546 
1547 e_free_trans:
1548 	kfree(trans);
1549 e_free_hdr:
1550 	kfree(hdr);
1551 
1552 	return ret;
1553 }
1554 
1555 static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1556 {
1557 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1558 	struct sev_data_receive_finish data;
1559 
1560 	if (!sev_guest(kvm))
1561 		return -ENOTTY;
1562 
1563 	data.handle = sev->handle;
1564 	return sev_issue_cmd(kvm, SEV_CMD_RECEIVE_FINISH, &data, &argp->error);
1565 }
1566 
1567 static bool is_cmd_allowed_from_mirror(u32 cmd_id)
1568 {
1569 	/*
1570 	 * Allow mirrors VM to call KVM_SEV_LAUNCH_UPDATE_VMSA to enable SEV-ES
1571 	 * active mirror VMs. Also allow the debugging and status commands.
1572 	 */
1573 	if (cmd_id == KVM_SEV_LAUNCH_UPDATE_VMSA ||
1574 	    cmd_id == KVM_SEV_GUEST_STATUS || cmd_id == KVM_SEV_DBG_DECRYPT ||
1575 	    cmd_id == KVM_SEV_DBG_ENCRYPT)
1576 		return true;
1577 
1578 	return false;
1579 }
1580 
1581 static int sev_lock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1582 {
1583 	struct kvm_sev_info *dst_sev = &to_kvm_svm(dst_kvm)->sev_info;
1584 	struct kvm_sev_info *src_sev = &to_kvm_svm(src_kvm)->sev_info;
1585 	int r = -EBUSY;
1586 
1587 	if (dst_kvm == src_kvm)
1588 		return -EINVAL;
1589 
1590 	/*
1591 	 * Bail if these VMs are already involved in a migration to avoid
1592 	 * deadlock between two VMs trying to migrate to/from each other.
1593 	 */
1594 	if (atomic_cmpxchg_acquire(&dst_sev->migration_in_progress, 0, 1))
1595 		return -EBUSY;
1596 
1597 	if (atomic_cmpxchg_acquire(&src_sev->migration_in_progress, 0, 1))
1598 		goto release_dst;
1599 
1600 	r = -EINTR;
1601 	if (mutex_lock_killable(&dst_kvm->lock))
1602 		goto release_src;
1603 	if (mutex_lock_killable_nested(&src_kvm->lock, SINGLE_DEPTH_NESTING))
1604 		goto unlock_dst;
1605 	return 0;
1606 
1607 unlock_dst:
1608 	mutex_unlock(&dst_kvm->lock);
1609 release_src:
1610 	atomic_set_release(&src_sev->migration_in_progress, 0);
1611 release_dst:
1612 	atomic_set_release(&dst_sev->migration_in_progress, 0);
1613 	return r;
1614 }
1615 
1616 static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1617 {
1618 	struct kvm_sev_info *dst_sev = &to_kvm_svm(dst_kvm)->sev_info;
1619 	struct kvm_sev_info *src_sev = &to_kvm_svm(src_kvm)->sev_info;
1620 
1621 	mutex_unlock(&dst_kvm->lock);
1622 	mutex_unlock(&src_kvm->lock);
1623 	atomic_set_release(&dst_sev->migration_in_progress, 0);
1624 	atomic_set_release(&src_sev->migration_in_progress, 0);
1625 }
1626 
1627 /* vCPU mutex subclasses.  */
1628 enum sev_migration_role {
1629 	SEV_MIGRATION_SOURCE = 0,
1630 	SEV_MIGRATION_TARGET,
1631 	SEV_NR_MIGRATION_ROLES,
1632 };
1633 
1634 static int sev_lock_vcpus_for_migration(struct kvm *kvm,
1635 					enum sev_migration_role role)
1636 {
1637 	struct kvm_vcpu *vcpu;
1638 	unsigned long i, j;
1639 
1640 	kvm_for_each_vcpu(i, vcpu, kvm) {
1641 		if (mutex_lock_killable_nested(&vcpu->mutex, role))
1642 			goto out_unlock;
1643 
1644 #ifdef CONFIG_PROVE_LOCKING
1645 		if (!i)
1646 			/*
1647 			 * Reset the role to one that avoids colliding with
1648 			 * the role used for the first vcpu mutex.
1649 			 */
1650 			role = SEV_NR_MIGRATION_ROLES;
1651 		else
1652 			mutex_release(&vcpu->mutex.dep_map, _THIS_IP_);
1653 #endif
1654 	}
1655 
1656 	return 0;
1657 
1658 out_unlock:
1659 
1660 	kvm_for_each_vcpu(j, vcpu, kvm) {
1661 		if (i == j)
1662 			break;
1663 
1664 #ifdef CONFIG_PROVE_LOCKING
1665 		if (j)
1666 			mutex_acquire(&vcpu->mutex.dep_map, role, 0, _THIS_IP_);
1667 #endif
1668 
1669 		mutex_unlock(&vcpu->mutex);
1670 	}
1671 	return -EINTR;
1672 }
1673 
1674 static void sev_unlock_vcpus_for_migration(struct kvm *kvm)
1675 {
1676 	struct kvm_vcpu *vcpu;
1677 	unsigned long i;
1678 	bool first = true;
1679 
1680 	kvm_for_each_vcpu(i, vcpu, kvm) {
1681 		if (first)
1682 			first = false;
1683 		else
1684 			mutex_acquire(&vcpu->mutex.dep_map,
1685 				      SEV_NR_MIGRATION_ROLES, 0, _THIS_IP_);
1686 
1687 		mutex_unlock(&vcpu->mutex);
1688 	}
1689 }
1690 
1691 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
1692 {
1693 	struct kvm_sev_info *dst = &to_kvm_svm(dst_kvm)->sev_info;
1694 	struct kvm_sev_info *src = &to_kvm_svm(src_kvm)->sev_info;
1695 	struct kvm_vcpu *dst_vcpu, *src_vcpu;
1696 	struct vcpu_svm *dst_svm, *src_svm;
1697 	struct kvm_sev_info *mirror;
1698 	unsigned long i;
1699 
1700 	dst->active = true;
1701 	dst->asid = src->asid;
1702 	dst->handle = src->handle;
1703 	dst->pages_locked = src->pages_locked;
1704 	dst->enc_context_owner = src->enc_context_owner;
1705 	dst->es_active = src->es_active;
1706 
1707 	src->asid = 0;
1708 	src->active = false;
1709 	src->handle = 0;
1710 	src->pages_locked = 0;
1711 	src->enc_context_owner = NULL;
1712 	src->es_active = false;
1713 
1714 	list_cut_before(&dst->regions_list, &src->regions_list, &src->regions_list);
1715 
1716 	/*
1717 	 * If this VM has mirrors, "transfer" each mirror's refcount of the
1718 	 * source to the destination (this KVM).  The caller holds a reference
1719 	 * to the source, so there's no danger of use-after-free.
1720 	 */
1721 	list_cut_before(&dst->mirror_vms, &src->mirror_vms, &src->mirror_vms);
1722 	list_for_each_entry(mirror, &dst->mirror_vms, mirror_entry) {
1723 		kvm_get_kvm(dst_kvm);
1724 		kvm_put_kvm(src_kvm);
1725 		mirror->enc_context_owner = dst_kvm;
1726 	}
1727 
1728 	/*
1729 	 * If this VM is a mirror, remove the old mirror from the owners list
1730 	 * and add the new mirror to the list.
1731 	 */
1732 	if (is_mirroring_enc_context(dst_kvm)) {
1733 		struct kvm_sev_info *owner_sev_info =
1734 			&to_kvm_svm(dst->enc_context_owner)->sev_info;
1735 
1736 		list_del(&src->mirror_entry);
1737 		list_add_tail(&dst->mirror_entry, &owner_sev_info->mirror_vms);
1738 	}
1739 
1740 	kvm_for_each_vcpu(i, dst_vcpu, dst_kvm) {
1741 		dst_svm = to_svm(dst_vcpu);
1742 
1743 		sev_init_vmcb(dst_svm);
1744 
1745 		if (!dst->es_active)
1746 			continue;
1747 
1748 		/*
1749 		 * Note, the source is not required to have the same number of
1750 		 * vCPUs as the destination when migrating a vanilla SEV VM.
1751 		 */
1752 		src_vcpu = kvm_get_vcpu(src_kvm, i);
1753 		src_svm = to_svm(src_vcpu);
1754 
1755 		/*
1756 		 * Transfer VMSA and GHCB state to the destination.  Nullify and
1757 		 * clear source fields as appropriate, the state now belongs to
1758 		 * the destination.
1759 		 */
1760 		memcpy(&dst_svm->sev_es, &src_svm->sev_es, sizeof(src_svm->sev_es));
1761 		dst_svm->vmcb->control.ghcb_gpa = src_svm->vmcb->control.ghcb_gpa;
1762 		dst_svm->vmcb->control.vmsa_pa = src_svm->vmcb->control.vmsa_pa;
1763 		dst_vcpu->arch.guest_state_protected = true;
1764 
1765 		memset(&src_svm->sev_es, 0, sizeof(src_svm->sev_es));
1766 		src_svm->vmcb->control.ghcb_gpa = INVALID_PAGE;
1767 		src_svm->vmcb->control.vmsa_pa = INVALID_PAGE;
1768 		src_vcpu->arch.guest_state_protected = false;
1769 	}
1770 }
1771 
1772 static int sev_check_source_vcpus(struct kvm *dst, struct kvm *src)
1773 {
1774 	struct kvm_vcpu *src_vcpu;
1775 	unsigned long i;
1776 
1777 	if (!sev_es_guest(src))
1778 		return 0;
1779 
1780 	if (atomic_read(&src->online_vcpus) != atomic_read(&dst->online_vcpus))
1781 		return -EINVAL;
1782 
1783 	kvm_for_each_vcpu(i, src_vcpu, src) {
1784 		if (!src_vcpu->arch.guest_state_protected)
1785 			return -EINVAL;
1786 	}
1787 
1788 	return 0;
1789 }
1790 
1791 int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
1792 {
1793 	struct kvm_sev_info *dst_sev = &to_kvm_svm(kvm)->sev_info;
1794 	struct kvm_sev_info *src_sev, *cg_cleanup_sev;
1795 	struct fd f = fdget(source_fd);
1796 	struct kvm *source_kvm;
1797 	bool charged = false;
1798 	int ret;
1799 
1800 	if (!f.file)
1801 		return -EBADF;
1802 
1803 	if (!file_is_kvm(f.file)) {
1804 		ret = -EBADF;
1805 		goto out_fput;
1806 	}
1807 
1808 	source_kvm = f.file->private_data;
1809 	ret = sev_lock_two_vms(kvm, source_kvm);
1810 	if (ret)
1811 		goto out_fput;
1812 
1813 	if (sev_guest(kvm) || !sev_guest(source_kvm)) {
1814 		ret = -EINVAL;
1815 		goto out_unlock;
1816 	}
1817 
1818 	src_sev = &to_kvm_svm(source_kvm)->sev_info;
1819 
1820 	dst_sev->misc_cg = get_current_misc_cg();
1821 	cg_cleanup_sev = dst_sev;
1822 	if (dst_sev->misc_cg != src_sev->misc_cg) {
1823 		ret = sev_misc_cg_try_charge(dst_sev);
1824 		if (ret)
1825 			goto out_dst_cgroup;
1826 		charged = true;
1827 	}
1828 
1829 	ret = sev_lock_vcpus_for_migration(kvm, SEV_MIGRATION_SOURCE);
1830 	if (ret)
1831 		goto out_dst_cgroup;
1832 	ret = sev_lock_vcpus_for_migration(source_kvm, SEV_MIGRATION_TARGET);
1833 	if (ret)
1834 		goto out_dst_vcpu;
1835 
1836 	ret = sev_check_source_vcpus(kvm, source_kvm);
1837 	if (ret)
1838 		goto out_source_vcpu;
1839 
1840 	sev_migrate_from(kvm, source_kvm);
1841 	kvm_vm_dead(source_kvm);
1842 	cg_cleanup_sev = src_sev;
1843 	ret = 0;
1844 
1845 out_source_vcpu:
1846 	sev_unlock_vcpus_for_migration(source_kvm);
1847 out_dst_vcpu:
1848 	sev_unlock_vcpus_for_migration(kvm);
1849 out_dst_cgroup:
1850 	/* Operates on the source on success, on the destination on failure.  */
1851 	if (charged)
1852 		sev_misc_cg_uncharge(cg_cleanup_sev);
1853 	put_misc_cg(cg_cleanup_sev->misc_cg);
1854 	cg_cleanup_sev->misc_cg = NULL;
1855 out_unlock:
1856 	sev_unlock_two_vms(kvm, source_kvm);
1857 out_fput:
1858 	fdput(f);
1859 	return ret;
1860 }
1861 
1862 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
1863 {
1864 	struct kvm_sev_cmd sev_cmd;
1865 	int r;
1866 
1867 	if (!sev_enabled)
1868 		return -ENOTTY;
1869 
1870 	if (!argp)
1871 		return 0;
1872 
1873 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
1874 		return -EFAULT;
1875 
1876 	mutex_lock(&kvm->lock);
1877 
1878 	/* Only the enc_context_owner handles some memory enc operations. */
1879 	if (is_mirroring_enc_context(kvm) &&
1880 	    !is_cmd_allowed_from_mirror(sev_cmd.id)) {
1881 		r = -EINVAL;
1882 		goto out;
1883 	}
1884 
1885 	switch (sev_cmd.id) {
1886 	case KVM_SEV_ES_INIT:
1887 		if (!sev_es_enabled) {
1888 			r = -ENOTTY;
1889 			goto out;
1890 		}
1891 		fallthrough;
1892 	case KVM_SEV_INIT:
1893 		r = sev_guest_init(kvm, &sev_cmd);
1894 		break;
1895 	case KVM_SEV_LAUNCH_START:
1896 		r = sev_launch_start(kvm, &sev_cmd);
1897 		break;
1898 	case KVM_SEV_LAUNCH_UPDATE_DATA:
1899 		r = sev_launch_update_data(kvm, &sev_cmd);
1900 		break;
1901 	case KVM_SEV_LAUNCH_UPDATE_VMSA:
1902 		r = sev_launch_update_vmsa(kvm, &sev_cmd);
1903 		break;
1904 	case KVM_SEV_LAUNCH_MEASURE:
1905 		r = sev_launch_measure(kvm, &sev_cmd);
1906 		break;
1907 	case KVM_SEV_LAUNCH_FINISH:
1908 		r = sev_launch_finish(kvm, &sev_cmd);
1909 		break;
1910 	case KVM_SEV_GUEST_STATUS:
1911 		r = sev_guest_status(kvm, &sev_cmd);
1912 		break;
1913 	case KVM_SEV_DBG_DECRYPT:
1914 		r = sev_dbg_crypt(kvm, &sev_cmd, true);
1915 		break;
1916 	case KVM_SEV_DBG_ENCRYPT:
1917 		r = sev_dbg_crypt(kvm, &sev_cmd, false);
1918 		break;
1919 	case KVM_SEV_LAUNCH_SECRET:
1920 		r = sev_launch_secret(kvm, &sev_cmd);
1921 		break;
1922 	case KVM_SEV_GET_ATTESTATION_REPORT:
1923 		r = sev_get_attestation_report(kvm, &sev_cmd);
1924 		break;
1925 	case KVM_SEV_SEND_START:
1926 		r = sev_send_start(kvm, &sev_cmd);
1927 		break;
1928 	case KVM_SEV_SEND_UPDATE_DATA:
1929 		r = sev_send_update_data(kvm, &sev_cmd);
1930 		break;
1931 	case KVM_SEV_SEND_FINISH:
1932 		r = sev_send_finish(kvm, &sev_cmd);
1933 		break;
1934 	case KVM_SEV_SEND_CANCEL:
1935 		r = sev_send_cancel(kvm, &sev_cmd);
1936 		break;
1937 	case KVM_SEV_RECEIVE_START:
1938 		r = sev_receive_start(kvm, &sev_cmd);
1939 		break;
1940 	case KVM_SEV_RECEIVE_UPDATE_DATA:
1941 		r = sev_receive_update_data(kvm, &sev_cmd);
1942 		break;
1943 	case KVM_SEV_RECEIVE_FINISH:
1944 		r = sev_receive_finish(kvm, &sev_cmd);
1945 		break;
1946 	default:
1947 		r = -EINVAL;
1948 		goto out;
1949 	}
1950 
1951 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
1952 		r = -EFAULT;
1953 
1954 out:
1955 	mutex_unlock(&kvm->lock);
1956 	return r;
1957 }
1958 
1959 int sev_mem_enc_register_region(struct kvm *kvm,
1960 				struct kvm_enc_region *range)
1961 {
1962 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1963 	struct enc_region *region;
1964 	int ret = 0;
1965 
1966 	if (!sev_guest(kvm))
1967 		return -ENOTTY;
1968 
1969 	/* If kvm is mirroring encryption context it isn't responsible for it */
1970 	if (is_mirroring_enc_context(kvm))
1971 		return -EINVAL;
1972 
1973 	if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
1974 		return -EINVAL;
1975 
1976 	region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
1977 	if (!region)
1978 		return -ENOMEM;
1979 
1980 	mutex_lock(&kvm->lock);
1981 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
1982 	if (IS_ERR(region->pages)) {
1983 		ret = PTR_ERR(region->pages);
1984 		mutex_unlock(&kvm->lock);
1985 		goto e_free;
1986 	}
1987 
1988 	/*
1989 	 * The guest may change the memory encryption attribute from C=0 -> C=1
1990 	 * or vice versa for this memory range. Lets make sure caches are
1991 	 * flushed to ensure that guest data gets written into memory with
1992 	 * correct C-bit.  Note, this must be done before dropping kvm->lock,
1993 	 * as region and its array of pages can be freed by a different task
1994 	 * once kvm->lock is released.
1995 	 */
1996 	sev_clflush_pages(region->pages, region->npages);
1997 
1998 	region->uaddr = range->addr;
1999 	region->size = range->size;
2000 
2001 	list_add_tail(&region->list, &sev->regions_list);
2002 	mutex_unlock(&kvm->lock);
2003 
2004 	return ret;
2005 
2006 e_free:
2007 	kfree(region);
2008 	return ret;
2009 }
2010 
2011 static struct enc_region *
2012 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
2013 {
2014 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2015 	struct list_head *head = &sev->regions_list;
2016 	struct enc_region *i;
2017 
2018 	list_for_each_entry(i, head, list) {
2019 		if (i->uaddr == range->addr &&
2020 		    i->size == range->size)
2021 			return i;
2022 	}
2023 
2024 	return NULL;
2025 }
2026 
2027 static void __unregister_enc_region_locked(struct kvm *kvm,
2028 					   struct enc_region *region)
2029 {
2030 	sev_unpin_memory(kvm, region->pages, region->npages);
2031 	list_del(&region->list);
2032 	kfree(region);
2033 }
2034 
2035 int sev_mem_enc_unregister_region(struct kvm *kvm,
2036 				  struct kvm_enc_region *range)
2037 {
2038 	struct enc_region *region;
2039 	int ret;
2040 
2041 	/* If kvm is mirroring encryption context it isn't responsible for it */
2042 	if (is_mirroring_enc_context(kvm))
2043 		return -EINVAL;
2044 
2045 	mutex_lock(&kvm->lock);
2046 
2047 	if (!sev_guest(kvm)) {
2048 		ret = -ENOTTY;
2049 		goto failed;
2050 	}
2051 
2052 	region = find_enc_region(kvm, range);
2053 	if (!region) {
2054 		ret = -EINVAL;
2055 		goto failed;
2056 	}
2057 
2058 	/*
2059 	 * Ensure that all guest tagged cache entries are flushed before
2060 	 * releasing the pages back to the system for use. CLFLUSH will
2061 	 * not do this, so issue a WBINVD.
2062 	 */
2063 	wbinvd_on_all_cpus();
2064 
2065 	__unregister_enc_region_locked(kvm, region);
2066 
2067 	mutex_unlock(&kvm->lock);
2068 	return 0;
2069 
2070 failed:
2071 	mutex_unlock(&kvm->lock);
2072 	return ret;
2073 }
2074 
2075 int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2076 {
2077 	struct fd f = fdget(source_fd);
2078 	struct kvm *source_kvm;
2079 	struct kvm_sev_info *source_sev, *mirror_sev;
2080 	int ret;
2081 
2082 	if (!f.file)
2083 		return -EBADF;
2084 
2085 	if (!file_is_kvm(f.file)) {
2086 		ret = -EBADF;
2087 		goto e_source_fput;
2088 	}
2089 
2090 	source_kvm = f.file->private_data;
2091 	ret = sev_lock_two_vms(kvm, source_kvm);
2092 	if (ret)
2093 		goto e_source_fput;
2094 
2095 	/*
2096 	 * Mirrors of mirrors should work, but let's not get silly.  Also
2097 	 * disallow out-of-band SEV/SEV-ES init if the target is already an
2098 	 * SEV guest, or if vCPUs have been created.  KVM relies on vCPUs being
2099 	 * created after SEV/SEV-ES initialization, e.g. to init intercepts.
2100 	 */
2101 	if (sev_guest(kvm) || !sev_guest(source_kvm) ||
2102 	    is_mirroring_enc_context(source_kvm) || kvm->created_vcpus) {
2103 		ret = -EINVAL;
2104 		goto e_unlock;
2105 	}
2106 
2107 	/*
2108 	 * The mirror kvm holds an enc_context_owner ref so its asid can't
2109 	 * disappear until we're done with it
2110 	 */
2111 	source_sev = &to_kvm_svm(source_kvm)->sev_info;
2112 	kvm_get_kvm(source_kvm);
2113 	mirror_sev = &to_kvm_svm(kvm)->sev_info;
2114 	list_add_tail(&mirror_sev->mirror_entry, &source_sev->mirror_vms);
2115 
2116 	/* Set enc_context_owner and copy its encryption context over */
2117 	mirror_sev->enc_context_owner = source_kvm;
2118 	mirror_sev->active = true;
2119 	mirror_sev->asid = source_sev->asid;
2120 	mirror_sev->fd = source_sev->fd;
2121 	mirror_sev->es_active = source_sev->es_active;
2122 	mirror_sev->handle = source_sev->handle;
2123 	INIT_LIST_HEAD(&mirror_sev->regions_list);
2124 	INIT_LIST_HEAD(&mirror_sev->mirror_vms);
2125 	ret = 0;
2126 
2127 	/*
2128 	 * Do not copy ap_jump_table. Since the mirror does not share the same
2129 	 * KVM contexts as the original, and they may have different
2130 	 * memory-views.
2131 	 */
2132 
2133 e_unlock:
2134 	sev_unlock_two_vms(kvm, source_kvm);
2135 e_source_fput:
2136 	fdput(f);
2137 	return ret;
2138 }
2139 
2140 void sev_vm_destroy(struct kvm *kvm)
2141 {
2142 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2143 	struct list_head *head = &sev->regions_list;
2144 	struct list_head *pos, *q;
2145 
2146 	if (!sev_guest(kvm))
2147 		return;
2148 
2149 	WARN_ON(!list_empty(&sev->mirror_vms));
2150 
2151 	/* If this is a mirror_kvm release the enc_context_owner and skip sev cleanup */
2152 	if (is_mirroring_enc_context(kvm)) {
2153 		struct kvm *owner_kvm = sev->enc_context_owner;
2154 
2155 		mutex_lock(&owner_kvm->lock);
2156 		list_del(&sev->mirror_entry);
2157 		mutex_unlock(&owner_kvm->lock);
2158 		kvm_put_kvm(owner_kvm);
2159 		return;
2160 	}
2161 
2162 	/*
2163 	 * Ensure that all guest tagged cache entries are flushed before
2164 	 * releasing the pages back to the system for use. CLFLUSH will
2165 	 * not do this, so issue a WBINVD.
2166 	 */
2167 	wbinvd_on_all_cpus();
2168 
2169 	/*
2170 	 * if userspace was terminated before unregistering the memory regions
2171 	 * then lets unpin all the registered memory.
2172 	 */
2173 	if (!list_empty(head)) {
2174 		list_for_each_safe(pos, q, head) {
2175 			__unregister_enc_region_locked(kvm,
2176 				list_entry(pos, struct enc_region, list));
2177 			cond_resched();
2178 		}
2179 	}
2180 
2181 	sev_unbind_asid(kvm, sev->handle);
2182 	sev_asid_free(sev);
2183 }
2184 
2185 void __init sev_set_cpu_caps(void)
2186 {
2187 	if (!sev_enabled)
2188 		kvm_cpu_cap_clear(X86_FEATURE_SEV);
2189 	if (!sev_es_enabled)
2190 		kvm_cpu_cap_clear(X86_FEATURE_SEV_ES);
2191 }
2192 
2193 void __init sev_hardware_setup(void)
2194 {
2195 #ifdef CONFIG_KVM_AMD_SEV
2196 	unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count;
2197 	bool sev_es_supported = false;
2198 	bool sev_supported = false;
2199 
2200 	if (!sev_enabled || !npt_enabled || !nrips)
2201 		goto out;
2202 
2203 	/*
2204 	 * SEV must obviously be supported in hardware.  Sanity check that the
2205 	 * CPU supports decode assists, which is mandatory for SEV guests to
2206 	 * support instruction emulation.
2207 	 */
2208 	if (!boot_cpu_has(X86_FEATURE_SEV) ||
2209 	    WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_DECODEASSISTS)))
2210 		goto out;
2211 
2212 	/* Retrieve SEV CPUID information */
2213 	cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
2214 
2215 	/* Set encryption bit location for SEV-ES guests */
2216 	sev_enc_bit = ebx & 0x3f;
2217 
2218 	/* Maximum number of encrypted guests supported simultaneously */
2219 	max_sev_asid = ecx;
2220 	if (!max_sev_asid)
2221 		goto out;
2222 
2223 	/* Minimum ASID value that should be used for SEV guest */
2224 	min_sev_asid = edx;
2225 	sev_me_mask = 1UL << (ebx & 0x3f);
2226 
2227 	/*
2228 	 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap,
2229 	 * even though it's never used, so that the bitmap is indexed by the
2230 	 * actual ASID.
2231 	 */
2232 	nr_asids = max_sev_asid + 1;
2233 	sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
2234 	if (!sev_asid_bitmap)
2235 		goto out;
2236 
2237 	sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
2238 	if (!sev_reclaim_asid_bitmap) {
2239 		bitmap_free(sev_asid_bitmap);
2240 		sev_asid_bitmap = NULL;
2241 		goto out;
2242 	}
2243 
2244 	if (min_sev_asid <= max_sev_asid) {
2245 		sev_asid_count = max_sev_asid - min_sev_asid + 1;
2246 		WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count));
2247 	}
2248 	sev_supported = true;
2249 
2250 	/* SEV-ES support requested? */
2251 	if (!sev_es_enabled)
2252 		goto out;
2253 
2254 	/*
2255 	 * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
2256 	 * instruction stream, i.e. can't emulate in response to a #NPF and
2257 	 * instead relies on #NPF(RSVD) being reflected into the guest as #VC
2258 	 * (the guest can then do a #VMGEXIT to request MMIO emulation).
2259 	 */
2260 	if (!enable_mmio_caching)
2261 		goto out;
2262 
2263 	/* Does the CPU support SEV-ES? */
2264 	if (!boot_cpu_has(X86_FEATURE_SEV_ES))
2265 		goto out;
2266 
2267 	/* Has the system been allocated ASIDs for SEV-ES? */
2268 	if (min_sev_asid == 1)
2269 		goto out;
2270 
2271 	sev_es_asid_count = min_sev_asid - 1;
2272 	WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count));
2273 	sev_es_supported = true;
2274 
2275 out:
2276 	if (boot_cpu_has(X86_FEATURE_SEV))
2277 		pr_info("SEV %s (ASIDs %u - %u)\n",
2278 			sev_supported ? min_sev_asid <= max_sev_asid ? "enabled" :
2279 								       "unusable" :
2280 								       "disabled",
2281 			min_sev_asid, max_sev_asid);
2282 	if (boot_cpu_has(X86_FEATURE_SEV_ES))
2283 		pr_info("SEV-ES %s (ASIDs %u - %u)\n",
2284 			sev_es_supported ? "enabled" : "disabled",
2285 			min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1);
2286 
2287 	sev_enabled = sev_supported;
2288 	sev_es_enabled = sev_es_supported;
2289 	if (!sev_es_enabled || !cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) ||
2290 	    !cpu_feature_enabled(X86_FEATURE_NO_NESTED_DATA_BP))
2291 		sev_es_debug_swap_enabled = false;
2292 #endif
2293 }
2294 
2295 void sev_hardware_unsetup(void)
2296 {
2297 	if (!sev_enabled)
2298 		return;
2299 
2300 	/* No need to take sev_bitmap_lock, all VMs have been destroyed. */
2301 	sev_flush_asids(1, max_sev_asid);
2302 
2303 	bitmap_free(sev_asid_bitmap);
2304 	bitmap_free(sev_reclaim_asid_bitmap);
2305 
2306 	misc_cg_set_capacity(MISC_CG_RES_SEV, 0);
2307 	misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0);
2308 }
2309 
2310 int sev_cpu_init(struct svm_cpu_data *sd)
2311 {
2312 	if (!sev_enabled)
2313 		return 0;
2314 
2315 	sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL);
2316 	if (!sd->sev_vmcbs)
2317 		return -ENOMEM;
2318 
2319 	return 0;
2320 }
2321 
2322 /*
2323  * Pages used by hardware to hold guest encrypted state must be flushed before
2324  * returning them to the system.
2325  */
2326 static void sev_flush_encrypted_page(struct kvm_vcpu *vcpu, void *va)
2327 {
2328 	unsigned int asid = sev_get_asid(vcpu->kvm);
2329 
2330 	/*
2331 	 * Note!  The address must be a kernel address, as regular page walk
2332 	 * checks are performed by VM_PAGE_FLUSH, i.e. operating on a user
2333 	 * address is non-deterministic and unsafe.  This function deliberately
2334 	 * takes a pointer to deter passing in a user address.
2335 	 */
2336 	unsigned long addr = (unsigned long)va;
2337 
2338 	/*
2339 	 * If CPU enforced cache coherency for encrypted mappings of the
2340 	 * same physical page is supported, use CLFLUSHOPT instead. NOTE: cache
2341 	 * flush is still needed in order to work properly with DMA devices.
2342 	 */
2343 	if (boot_cpu_has(X86_FEATURE_SME_COHERENT)) {
2344 		clflush_cache_range(va, PAGE_SIZE);
2345 		return;
2346 	}
2347 
2348 	/*
2349 	 * VM Page Flush takes a host virtual address and a guest ASID.  Fall
2350 	 * back to WBINVD if this faults so as not to make any problems worse
2351 	 * by leaving stale encrypted data in the cache.
2352 	 */
2353 	if (WARN_ON_ONCE(wrmsrl_safe(MSR_AMD64_VM_PAGE_FLUSH, addr | asid)))
2354 		goto do_wbinvd;
2355 
2356 	return;
2357 
2358 do_wbinvd:
2359 	wbinvd_on_all_cpus();
2360 }
2361 
2362 void sev_guest_memory_reclaimed(struct kvm *kvm)
2363 {
2364 	if (!sev_guest(kvm))
2365 		return;
2366 
2367 	wbinvd_on_all_cpus();
2368 }
2369 
2370 void sev_free_vcpu(struct kvm_vcpu *vcpu)
2371 {
2372 	struct vcpu_svm *svm;
2373 
2374 	if (!sev_es_guest(vcpu->kvm))
2375 		return;
2376 
2377 	svm = to_svm(vcpu);
2378 
2379 	if (vcpu->arch.guest_state_protected)
2380 		sev_flush_encrypted_page(vcpu, svm->sev_es.vmsa);
2381 
2382 	__free_page(virt_to_page(svm->sev_es.vmsa));
2383 
2384 	if (svm->sev_es.ghcb_sa_free)
2385 		kvfree(svm->sev_es.ghcb_sa);
2386 }
2387 
2388 static void dump_ghcb(struct vcpu_svm *svm)
2389 {
2390 	struct ghcb *ghcb = svm->sev_es.ghcb;
2391 	unsigned int nbits;
2392 
2393 	/* Re-use the dump_invalid_vmcb module parameter */
2394 	if (!dump_invalid_vmcb) {
2395 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
2396 		return;
2397 	}
2398 
2399 	nbits = sizeof(ghcb->save.valid_bitmap) * 8;
2400 
2401 	pr_err("GHCB (GPA=%016llx):\n", svm->vmcb->control.ghcb_gpa);
2402 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
2403 	       ghcb->save.sw_exit_code, ghcb_sw_exit_code_is_valid(ghcb));
2404 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
2405 	       ghcb->save.sw_exit_info_1, ghcb_sw_exit_info_1_is_valid(ghcb));
2406 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
2407 	       ghcb->save.sw_exit_info_2, ghcb_sw_exit_info_2_is_valid(ghcb));
2408 	pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
2409 	       ghcb->save.sw_scratch, ghcb_sw_scratch_is_valid(ghcb));
2410 	pr_err("%-20s%*pb\n", "valid_bitmap", nbits, ghcb->save.valid_bitmap);
2411 }
2412 
2413 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
2414 {
2415 	struct kvm_vcpu *vcpu = &svm->vcpu;
2416 	struct ghcb *ghcb = svm->sev_es.ghcb;
2417 
2418 	/*
2419 	 * The GHCB protocol so far allows for the following data
2420 	 * to be returned:
2421 	 *   GPRs RAX, RBX, RCX, RDX
2422 	 *
2423 	 * Copy their values, even if they may not have been written during the
2424 	 * VM-Exit.  It's the guest's responsibility to not consume random data.
2425 	 */
2426 	ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
2427 	ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
2428 	ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
2429 	ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
2430 }
2431 
2432 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
2433 {
2434 	struct vmcb_control_area *control = &svm->vmcb->control;
2435 	struct kvm_vcpu *vcpu = &svm->vcpu;
2436 	struct ghcb *ghcb = svm->sev_es.ghcb;
2437 	u64 exit_code;
2438 
2439 	/*
2440 	 * The GHCB protocol so far allows for the following data
2441 	 * to be supplied:
2442 	 *   GPRs RAX, RBX, RCX, RDX
2443 	 *   XCR0
2444 	 *   CPL
2445 	 *
2446 	 * VMMCALL allows the guest to provide extra registers. KVM also
2447 	 * expects RSI for hypercalls, so include that, too.
2448 	 *
2449 	 * Copy their values to the appropriate location if supplied.
2450 	 */
2451 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
2452 
2453 	BUILD_BUG_ON(sizeof(svm->sev_es.valid_bitmap) != sizeof(ghcb->save.valid_bitmap));
2454 	memcpy(&svm->sev_es.valid_bitmap, &ghcb->save.valid_bitmap, sizeof(ghcb->save.valid_bitmap));
2455 
2456 	vcpu->arch.regs[VCPU_REGS_RAX] = kvm_ghcb_get_rax_if_valid(svm, ghcb);
2457 	vcpu->arch.regs[VCPU_REGS_RBX] = kvm_ghcb_get_rbx_if_valid(svm, ghcb);
2458 	vcpu->arch.regs[VCPU_REGS_RCX] = kvm_ghcb_get_rcx_if_valid(svm, ghcb);
2459 	vcpu->arch.regs[VCPU_REGS_RDX] = kvm_ghcb_get_rdx_if_valid(svm, ghcb);
2460 	vcpu->arch.regs[VCPU_REGS_RSI] = kvm_ghcb_get_rsi_if_valid(svm, ghcb);
2461 
2462 	svm->vmcb->save.cpl = kvm_ghcb_get_cpl_if_valid(svm, ghcb);
2463 
2464 	if (kvm_ghcb_xcr0_is_valid(svm)) {
2465 		vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb);
2466 		kvm_update_cpuid_runtime(vcpu);
2467 	}
2468 
2469 	/* Copy the GHCB exit information into the VMCB fields */
2470 	exit_code = ghcb_get_sw_exit_code(ghcb);
2471 	control->exit_code = lower_32_bits(exit_code);
2472 	control->exit_code_hi = upper_32_bits(exit_code);
2473 	control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb);
2474 	control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb);
2475 	svm->sev_es.sw_scratch = kvm_ghcb_get_sw_scratch_if_valid(svm, ghcb);
2476 
2477 	/* Clear the valid entries fields */
2478 	memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
2479 }
2480 
2481 static u64 kvm_ghcb_get_sw_exit_code(struct vmcb_control_area *control)
2482 {
2483 	return (((u64)control->exit_code_hi) << 32) | control->exit_code;
2484 }
2485 
2486 static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
2487 {
2488 	struct vmcb_control_area *control = &svm->vmcb->control;
2489 	struct kvm_vcpu *vcpu = &svm->vcpu;
2490 	u64 exit_code;
2491 	u64 reason;
2492 
2493 	/*
2494 	 * Retrieve the exit code now even though it may not be marked valid
2495 	 * as it could help with debugging.
2496 	 */
2497 	exit_code = kvm_ghcb_get_sw_exit_code(control);
2498 
2499 	/* Only GHCB Usage code 0 is supported */
2500 	if (svm->sev_es.ghcb->ghcb_usage) {
2501 		reason = GHCB_ERR_INVALID_USAGE;
2502 		goto vmgexit_err;
2503 	}
2504 
2505 	reason = GHCB_ERR_MISSING_INPUT;
2506 
2507 	if (!kvm_ghcb_sw_exit_code_is_valid(svm) ||
2508 	    !kvm_ghcb_sw_exit_info_1_is_valid(svm) ||
2509 	    !kvm_ghcb_sw_exit_info_2_is_valid(svm))
2510 		goto vmgexit_err;
2511 
2512 	switch (exit_code) {
2513 	case SVM_EXIT_READ_DR7:
2514 		break;
2515 	case SVM_EXIT_WRITE_DR7:
2516 		if (!kvm_ghcb_rax_is_valid(svm))
2517 			goto vmgexit_err;
2518 		break;
2519 	case SVM_EXIT_RDTSC:
2520 		break;
2521 	case SVM_EXIT_RDPMC:
2522 		if (!kvm_ghcb_rcx_is_valid(svm))
2523 			goto vmgexit_err;
2524 		break;
2525 	case SVM_EXIT_CPUID:
2526 		if (!kvm_ghcb_rax_is_valid(svm) ||
2527 		    !kvm_ghcb_rcx_is_valid(svm))
2528 			goto vmgexit_err;
2529 		if (vcpu->arch.regs[VCPU_REGS_RAX] == 0xd)
2530 			if (!kvm_ghcb_xcr0_is_valid(svm))
2531 				goto vmgexit_err;
2532 		break;
2533 	case SVM_EXIT_INVD:
2534 		break;
2535 	case SVM_EXIT_IOIO:
2536 		if (control->exit_info_1 & SVM_IOIO_STR_MASK) {
2537 			if (!kvm_ghcb_sw_scratch_is_valid(svm))
2538 				goto vmgexit_err;
2539 		} else {
2540 			if (!(control->exit_info_1 & SVM_IOIO_TYPE_MASK))
2541 				if (!kvm_ghcb_rax_is_valid(svm))
2542 					goto vmgexit_err;
2543 		}
2544 		break;
2545 	case SVM_EXIT_MSR:
2546 		if (!kvm_ghcb_rcx_is_valid(svm))
2547 			goto vmgexit_err;
2548 		if (control->exit_info_1) {
2549 			if (!kvm_ghcb_rax_is_valid(svm) ||
2550 			    !kvm_ghcb_rdx_is_valid(svm))
2551 				goto vmgexit_err;
2552 		}
2553 		break;
2554 	case SVM_EXIT_VMMCALL:
2555 		if (!kvm_ghcb_rax_is_valid(svm) ||
2556 		    !kvm_ghcb_cpl_is_valid(svm))
2557 			goto vmgexit_err;
2558 		break;
2559 	case SVM_EXIT_RDTSCP:
2560 		break;
2561 	case SVM_EXIT_WBINVD:
2562 		break;
2563 	case SVM_EXIT_MONITOR:
2564 		if (!kvm_ghcb_rax_is_valid(svm) ||
2565 		    !kvm_ghcb_rcx_is_valid(svm) ||
2566 		    !kvm_ghcb_rdx_is_valid(svm))
2567 			goto vmgexit_err;
2568 		break;
2569 	case SVM_EXIT_MWAIT:
2570 		if (!kvm_ghcb_rax_is_valid(svm) ||
2571 		    !kvm_ghcb_rcx_is_valid(svm))
2572 			goto vmgexit_err;
2573 		break;
2574 	case SVM_VMGEXIT_MMIO_READ:
2575 	case SVM_VMGEXIT_MMIO_WRITE:
2576 		if (!kvm_ghcb_sw_scratch_is_valid(svm))
2577 			goto vmgexit_err;
2578 		break;
2579 	case SVM_VMGEXIT_NMI_COMPLETE:
2580 	case SVM_VMGEXIT_AP_HLT_LOOP:
2581 	case SVM_VMGEXIT_AP_JUMP_TABLE:
2582 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
2583 		break;
2584 	default:
2585 		reason = GHCB_ERR_INVALID_EVENT;
2586 		goto vmgexit_err;
2587 	}
2588 
2589 	return 0;
2590 
2591 vmgexit_err:
2592 	if (reason == GHCB_ERR_INVALID_USAGE) {
2593 		vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
2594 			    svm->sev_es.ghcb->ghcb_usage);
2595 	} else if (reason == GHCB_ERR_INVALID_EVENT) {
2596 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is not valid\n",
2597 			    exit_code);
2598 	} else {
2599 		vcpu_unimpl(vcpu, "vmgexit: exit code %#llx input is not valid\n",
2600 			    exit_code);
2601 		dump_ghcb(svm);
2602 	}
2603 
2604 	ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
2605 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, reason);
2606 
2607 	/* Resume the guest to "return" the error code. */
2608 	return 1;
2609 }
2610 
2611 void sev_es_unmap_ghcb(struct vcpu_svm *svm)
2612 {
2613 	if (!svm->sev_es.ghcb)
2614 		return;
2615 
2616 	if (svm->sev_es.ghcb_sa_free) {
2617 		/*
2618 		 * The scratch area lives outside the GHCB, so there is a
2619 		 * buffer that, depending on the operation performed, may
2620 		 * need to be synced, then freed.
2621 		 */
2622 		if (svm->sev_es.ghcb_sa_sync) {
2623 			kvm_write_guest(svm->vcpu.kvm,
2624 					svm->sev_es.sw_scratch,
2625 					svm->sev_es.ghcb_sa,
2626 					svm->sev_es.ghcb_sa_len);
2627 			svm->sev_es.ghcb_sa_sync = false;
2628 		}
2629 
2630 		kvfree(svm->sev_es.ghcb_sa);
2631 		svm->sev_es.ghcb_sa = NULL;
2632 		svm->sev_es.ghcb_sa_free = false;
2633 	}
2634 
2635 	trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->sev_es.ghcb);
2636 
2637 	sev_es_sync_to_ghcb(svm);
2638 
2639 	kvm_vcpu_unmap(&svm->vcpu, &svm->sev_es.ghcb_map, true);
2640 	svm->sev_es.ghcb = NULL;
2641 }
2642 
2643 void pre_sev_run(struct vcpu_svm *svm, int cpu)
2644 {
2645 	struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
2646 	unsigned int asid = sev_get_asid(svm->vcpu.kvm);
2647 
2648 	/* Assign the asid allocated with this SEV guest */
2649 	svm->asid = asid;
2650 
2651 	/*
2652 	 * Flush guest TLB:
2653 	 *
2654 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
2655 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
2656 	 */
2657 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
2658 	    svm->vcpu.arch.last_vmentry_cpu == cpu)
2659 		return;
2660 
2661 	sd->sev_vmcbs[asid] = svm->vmcb;
2662 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
2663 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
2664 }
2665 
2666 #define GHCB_SCRATCH_AREA_LIMIT		(16ULL * PAGE_SIZE)
2667 static int setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len)
2668 {
2669 	struct vmcb_control_area *control = &svm->vmcb->control;
2670 	u64 ghcb_scratch_beg, ghcb_scratch_end;
2671 	u64 scratch_gpa_beg, scratch_gpa_end;
2672 	void *scratch_va;
2673 
2674 	scratch_gpa_beg = svm->sev_es.sw_scratch;
2675 	if (!scratch_gpa_beg) {
2676 		pr_err("vmgexit: scratch gpa not provided\n");
2677 		goto e_scratch;
2678 	}
2679 
2680 	scratch_gpa_end = scratch_gpa_beg + len;
2681 	if (scratch_gpa_end < scratch_gpa_beg) {
2682 		pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
2683 		       len, scratch_gpa_beg);
2684 		goto e_scratch;
2685 	}
2686 
2687 	if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
2688 		/* Scratch area begins within GHCB */
2689 		ghcb_scratch_beg = control->ghcb_gpa +
2690 				   offsetof(struct ghcb, shared_buffer);
2691 		ghcb_scratch_end = control->ghcb_gpa +
2692 				   offsetof(struct ghcb, reserved_0xff0);
2693 
2694 		/*
2695 		 * If the scratch area begins within the GHCB, it must be
2696 		 * completely contained in the GHCB shared buffer area.
2697 		 */
2698 		if (scratch_gpa_beg < ghcb_scratch_beg ||
2699 		    scratch_gpa_end > ghcb_scratch_end) {
2700 			pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
2701 			       scratch_gpa_beg, scratch_gpa_end);
2702 			goto e_scratch;
2703 		}
2704 
2705 		scratch_va = (void *)svm->sev_es.ghcb;
2706 		scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
2707 	} else {
2708 		/*
2709 		 * The guest memory must be read into a kernel buffer, so
2710 		 * limit the size
2711 		 */
2712 		if (len > GHCB_SCRATCH_AREA_LIMIT) {
2713 			pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
2714 			       len, GHCB_SCRATCH_AREA_LIMIT);
2715 			goto e_scratch;
2716 		}
2717 		scratch_va = kvzalloc(len, GFP_KERNEL_ACCOUNT);
2718 		if (!scratch_va)
2719 			return -ENOMEM;
2720 
2721 		if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) {
2722 			/* Unable to copy scratch area from guest */
2723 			pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
2724 
2725 			kvfree(scratch_va);
2726 			return -EFAULT;
2727 		}
2728 
2729 		/*
2730 		 * The scratch area is outside the GHCB. The operation will
2731 		 * dictate whether the buffer needs to be synced before running
2732 		 * the vCPU next time (i.e. a read was requested so the data
2733 		 * must be written back to the guest memory).
2734 		 */
2735 		svm->sev_es.ghcb_sa_sync = sync;
2736 		svm->sev_es.ghcb_sa_free = true;
2737 	}
2738 
2739 	svm->sev_es.ghcb_sa = scratch_va;
2740 	svm->sev_es.ghcb_sa_len = len;
2741 
2742 	return 0;
2743 
2744 e_scratch:
2745 	ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
2746 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_SCRATCH_AREA);
2747 
2748 	return 1;
2749 }
2750 
2751 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
2752 			      unsigned int pos)
2753 {
2754 	svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
2755 	svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
2756 }
2757 
2758 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
2759 {
2760 	return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
2761 }
2762 
2763 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
2764 {
2765 	svm->vmcb->control.ghcb_gpa = value;
2766 }
2767 
2768 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
2769 {
2770 	struct vmcb_control_area *control = &svm->vmcb->control;
2771 	struct kvm_vcpu *vcpu = &svm->vcpu;
2772 	u64 ghcb_info;
2773 	int ret = 1;
2774 
2775 	ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
2776 
2777 	trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
2778 					     control->ghcb_gpa);
2779 
2780 	switch (ghcb_info) {
2781 	case GHCB_MSR_SEV_INFO_REQ:
2782 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
2783 						    GHCB_VERSION_MIN,
2784 						    sev_enc_bit));
2785 		break;
2786 	case GHCB_MSR_CPUID_REQ: {
2787 		u64 cpuid_fn, cpuid_reg, cpuid_value;
2788 
2789 		cpuid_fn = get_ghcb_msr_bits(svm,
2790 					     GHCB_MSR_CPUID_FUNC_MASK,
2791 					     GHCB_MSR_CPUID_FUNC_POS);
2792 
2793 		/* Initialize the registers needed by the CPUID intercept */
2794 		vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
2795 		vcpu->arch.regs[VCPU_REGS_RCX] = 0;
2796 
2797 		ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
2798 		if (!ret) {
2799 			/* Error, keep GHCB MSR value as-is */
2800 			break;
2801 		}
2802 
2803 		cpuid_reg = get_ghcb_msr_bits(svm,
2804 					      GHCB_MSR_CPUID_REG_MASK,
2805 					      GHCB_MSR_CPUID_REG_POS);
2806 		if (cpuid_reg == 0)
2807 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
2808 		else if (cpuid_reg == 1)
2809 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
2810 		else if (cpuid_reg == 2)
2811 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
2812 		else
2813 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
2814 
2815 		set_ghcb_msr_bits(svm, cpuid_value,
2816 				  GHCB_MSR_CPUID_VALUE_MASK,
2817 				  GHCB_MSR_CPUID_VALUE_POS);
2818 
2819 		set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
2820 				  GHCB_MSR_INFO_MASK,
2821 				  GHCB_MSR_INFO_POS);
2822 		break;
2823 	}
2824 	case GHCB_MSR_TERM_REQ: {
2825 		u64 reason_set, reason_code;
2826 
2827 		reason_set = get_ghcb_msr_bits(svm,
2828 					       GHCB_MSR_TERM_REASON_SET_MASK,
2829 					       GHCB_MSR_TERM_REASON_SET_POS);
2830 		reason_code = get_ghcb_msr_bits(svm,
2831 						GHCB_MSR_TERM_REASON_MASK,
2832 						GHCB_MSR_TERM_REASON_POS);
2833 		pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
2834 			reason_set, reason_code);
2835 
2836 		vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
2837 		vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
2838 		vcpu->run->system_event.ndata = 1;
2839 		vcpu->run->system_event.data[0] = control->ghcb_gpa;
2840 
2841 		return 0;
2842 	}
2843 	default:
2844 		/* Error, keep GHCB MSR value as-is */
2845 		break;
2846 	}
2847 
2848 	trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
2849 					    control->ghcb_gpa, ret);
2850 
2851 	return ret;
2852 }
2853 
2854 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
2855 {
2856 	struct vcpu_svm *svm = to_svm(vcpu);
2857 	struct vmcb_control_area *control = &svm->vmcb->control;
2858 	u64 ghcb_gpa, exit_code;
2859 	int ret;
2860 
2861 	/* Validate the GHCB */
2862 	ghcb_gpa = control->ghcb_gpa;
2863 	if (ghcb_gpa & GHCB_MSR_INFO_MASK)
2864 		return sev_handle_vmgexit_msr_protocol(svm);
2865 
2866 	if (!ghcb_gpa) {
2867 		vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n");
2868 
2869 		/* Without a GHCB, just return right back to the guest */
2870 		return 1;
2871 	}
2872 
2873 	if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->sev_es.ghcb_map)) {
2874 		/* Unable to map GHCB from guest */
2875 		vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
2876 			    ghcb_gpa);
2877 
2878 		/* Without a GHCB, just return right back to the guest */
2879 		return 1;
2880 	}
2881 
2882 	svm->sev_es.ghcb = svm->sev_es.ghcb_map.hva;
2883 
2884 	trace_kvm_vmgexit_enter(vcpu->vcpu_id, svm->sev_es.ghcb);
2885 
2886 	sev_es_sync_from_ghcb(svm);
2887 	ret = sev_es_validate_vmgexit(svm);
2888 	if (ret)
2889 		return ret;
2890 
2891 	ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 0);
2892 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 0);
2893 
2894 	exit_code = kvm_ghcb_get_sw_exit_code(control);
2895 	switch (exit_code) {
2896 	case SVM_VMGEXIT_MMIO_READ:
2897 		ret = setup_vmgexit_scratch(svm, true, control->exit_info_2);
2898 		if (ret)
2899 			break;
2900 
2901 		ret = kvm_sev_es_mmio_read(vcpu,
2902 					   control->exit_info_1,
2903 					   control->exit_info_2,
2904 					   svm->sev_es.ghcb_sa);
2905 		break;
2906 	case SVM_VMGEXIT_MMIO_WRITE:
2907 		ret = setup_vmgexit_scratch(svm, false, control->exit_info_2);
2908 		if (ret)
2909 			break;
2910 
2911 		ret = kvm_sev_es_mmio_write(vcpu,
2912 					    control->exit_info_1,
2913 					    control->exit_info_2,
2914 					    svm->sev_es.ghcb_sa);
2915 		break;
2916 	case SVM_VMGEXIT_NMI_COMPLETE:
2917 		++vcpu->stat.nmi_window_exits;
2918 		svm->nmi_masked = false;
2919 		kvm_make_request(KVM_REQ_EVENT, vcpu);
2920 		ret = 1;
2921 		break;
2922 	case SVM_VMGEXIT_AP_HLT_LOOP:
2923 		ret = kvm_emulate_ap_reset_hold(vcpu);
2924 		break;
2925 	case SVM_VMGEXIT_AP_JUMP_TABLE: {
2926 		struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
2927 
2928 		switch (control->exit_info_1) {
2929 		case 0:
2930 			/* Set AP jump table address */
2931 			sev->ap_jump_table = control->exit_info_2;
2932 			break;
2933 		case 1:
2934 			/* Get AP jump table address */
2935 			ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, sev->ap_jump_table);
2936 			break;
2937 		default:
2938 			pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
2939 			       control->exit_info_1);
2940 			ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
2941 			ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_INPUT);
2942 		}
2943 
2944 		ret = 1;
2945 		break;
2946 	}
2947 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
2948 		vcpu_unimpl(vcpu,
2949 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
2950 			    control->exit_info_1, control->exit_info_2);
2951 		ret = -EINVAL;
2952 		break;
2953 	default:
2954 		ret = svm_invoke_exit_handler(vcpu, exit_code);
2955 	}
2956 
2957 	return ret;
2958 }
2959 
2960 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
2961 {
2962 	int count;
2963 	int bytes;
2964 	int r;
2965 
2966 	if (svm->vmcb->control.exit_info_2 > INT_MAX)
2967 		return -EINVAL;
2968 
2969 	count = svm->vmcb->control.exit_info_2;
2970 	if (unlikely(check_mul_overflow(count, size, &bytes)))
2971 		return -EINVAL;
2972 
2973 	r = setup_vmgexit_scratch(svm, in, bytes);
2974 	if (r)
2975 		return r;
2976 
2977 	return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->sev_es.ghcb_sa,
2978 				    count, in);
2979 }
2980 
2981 static void sev_es_vcpu_after_set_cpuid(struct vcpu_svm *svm)
2982 {
2983 	struct kvm_vcpu *vcpu = &svm->vcpu;
2984 
2985 	if (boot_cpu_has(X86_FEATURE_V_TSC_AUX)) {
2986 		bool v_tsc_aux = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
2987 				 guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
2988 
2989 		set_msr_interception(vcpu, svm->msrpm, MSR_TSC_AUX, v_tsc_aux, v_tsc_aux);
2990 	}
2991 }
2992 
2993 void sev_vcpu_after_set_cpuid(struct vcpu_svm *svm)
2994 {
2995 	struct kvm_vcpu *vcpu = &svm->vcpu;
2996 	struct kvm_cpuid_entry2 *best;
2997 
2998 	/* For sev guests, the memory encryption bit is not reserved in CR3.  */
2999 	best = kvm_find_cpuid_entry(vcpu, 0x8000001F);
3000 	if (best)
3001 		vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
3002 
3003 	if (sev_es_guest(svm->vcpu.kvm))
3004 		sev_es_vcpu_after_set_cpuid(svm);
3005 }
3006 
3007 static void sev_es_init_vmcb(struct vcpu_svm *svm)
3008 {
3009 	struct vmcb *vmcb = svm->vmcb01.ptr;
3010 	struct kvm_vcpu *vcpu = &svm->vcpu;
3011 
3012 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE;
3013 	svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
3014 
3015 	/*
3016 	 * An SEV-ES guest requires a VMSA area that is a separate from the
3017 	 * VMCB page. Do not include the encryption mask on the VMSA physical
3018 	 * address since hardware will access it using the guest key.  Note,
3019 	 * the VMSA will be NULL if this vCPU is the destination for intrahost
3020 	 * migration, and will be copied later.
3021 	 */
3022 	if (svm->sev_es.vmsa)
3023 		svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa);
3024 
3025 	/* Can't intercept CR register access, HV can't modify CR registers */
3026 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
3027 	svm_clr_intercept(svm, INTERCEPT_CR4_READ);
3028 	svm_clr_intercept(svm, INTERCEPT_CR8_READ);
3029 	svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
3030 	svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
3031 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3032 
3033 	svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
3034 
3035 	/* Track EFER/CR register changes */
3036 	svm_set_intercept(svm, TRAP_EFER_WRITE);
3037 	svm_set_intercept(svm, TRAP_CR0_WRITE);
3038 	svm_set_intercept(svm, TRAP_CR4_WRITE);
3039 	svm_set_intercept(svm, TRAP_CR8_WRITE);
3040 
3041 	vmcb->control.intercepts[INTERCEPT_DR] = 0;
3042 	if (!sev_es_debug_swap_enabled) {
3043 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
3044 		vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
3045 		recalc_intercepts(svm);
3046 	} else {
3047 		/*
3048 		 * Disable #DB intercept iff DebugSwap is enabled.  KVM doesn't
3049 		 * allow debugging SEV-ES guests, and enables DebugSwap iff
3050 		 * NO_NESTED_DATA_BP is supported, so there's no reason to
3051 		 * intercept #DB when DebugSwap is enabled.  For simplicity
3052 		 * with respect to guest debug, intercept #DB for other VMs
3053 		 * even if NO_NESTED_DATA_BP is supported, i.e. even if the
3054 		 * guest can't DoS the CPU with infinite #DB vectoring.
3055 		 */
3056 		clr_exception_intercept(svm, DB_VECTOR);
3057 	}
3058 
3059 	/* Can't intercept XSETBV, HV can't modify XCR0 directly */
3060 	svm_clr_intercept(svm, INTERCEPT_XSETBV);
3061 
3062 	/* Clear intercepts on selected MSRs */
3063 	set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1);
3064 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1);
3065 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
3066 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
3067 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
3068 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
3069 }
3070 
3071 void sev_init_vmcb(struct vcpu_svm *svm)
3072 {
3073 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
3074 	clr_exception_intercept(svm, UD_VECTOR);
3075 
3076 	/*
3077 	 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as
3078 	 * KVM can't decrypt guest memory to decode the faulting instruction.
3079 	 */
3080 	clr_exception_intercept(svm, GP_VECTOR);
3081 
3082 	if (sev_es_guest(svm->vcpu.kvm))
3083 		sev_es_init_vmcb(svm);
3084 }
3085 
3086 void sev_es_vcpu_reset(struct vcpu_svm *svm)
3087 {
3088 	/*
3089 	 * Set the GHCB MSR value as per the GHCB specification when emulating
3090 	 * vCPU RESET for an SEV-ES guest.
3091 	 */
3092 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
3093 					    GHCB_VERSION_MIN,
3094 					    sev_enc_bit));
3095 }
3096 
3097 void sev_es_prepare_switch_to_guest(struct sev_es_save_area *hostsa)
3098 {
3099 	/*
3100 	 * All host state for SEV-ES guests is categorized into three swap types
3101 	 * based on how it is handled by hardware during a world switch:
3102 	 *
3103 	 * A: VMRUN:   Host state saved in host save area
3104 	 *    VMEXIT:  Host state loaded from host save area
3105 	 *
3106 	 * B: VMRUN:   Host state _NOT_ saved in host save area
3107 	 *    VMEXIT:  Host state loaded from host save area
3108 	 *
3109 	 * C: VMRUN:   Host state _NOT_ saved in host save area
3110 	 *    VMEXIT:  Host state initialized to default(reset) values
3111 	 *
3112 	 * Manually save type-B state, i.e. state that is loaded by VMEXIT but
3113 	 * isn't saved by VMRUN, that isn't already saved by VMSAVE (performed
3114 	 * by common SVM code).
3115 	 */
3116 	hostsa->xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
3117 	hostsa->pkru = read_pkru();
3118 	hostsa->xss = host_xss;
3119 
3120 	/*
3121 	 * If DebugSwap is enabled, debug registers are loaded but NOT saved by
3122 	 * the CPU (Type-B). If DebugSwap is disabled/unsupported, the CPU both
3123 	 * saves and loads debug registers (Type-A).
3124 	 */
3125 	if (sev_es_debug_swap_enabled) {
3126 		hostsa->dr0 = native_get_debugreg(0);
3127 		hostsa->dr1 = native_get_debugreg(1);
3128 		hostsa->dr2 = native_get_debugreg(2);
3129 		hostsa->dr3 = native_get_debugreg(3);
3130 		hostsa->dr0_addr_mask = amd_get_dr_addr_mask(0);
3131 		hostsa->dr1_addr_mask = amd_get_dr_addr_mask(1);
3132 		hostsa->dr2_addr_mask = amd_get_dr_addr_mask(2);
3133 		hostsa->dr3_addr_mask = amd_get_dr_addr_mask(3);
3134 	}
3135 }
3136 
3137 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
3138 {
3139 	struct vcpu_svm *svm = to_svm(vcpu);
3140 
3141 	/* First SIPI: Use the values as initially set by the VMM */
3142 	if (!svm->sev_es.received_first_sipi) {
3143 		svm->sev_es.received_first_sipi = true;
3144 		return;
3145 	}
3146 
3147 	/*
3148 	 * Subsequent SIPI: Return from an AP Reset Hold VMGEXIT, where
3149 	 * the guest will set the CS and RIP. Set SW_EXIT_INFO_2 to a
3150 	 * non-zero value.
3151 	 */
3152 	if (!svm->sev_es.ghcb)
3153 		return;
3154 
3155 	ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 1);
3156 }
3157