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