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