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