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