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