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