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