xref: /openbmc/linux/arch/x86/kvm/svm/sev.c (revision 6cd70754)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM-SEV support
6  *
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  */
9 
10 #include <linux/kvm_types.h>
11 #include <linux/kvm_host.h>
12 #include <linux/kernel.h>
13 #include <linux/highmem.h>
14 #include <linux/psp-sev.h>
15 #include <linux/pagemap.h>
16 #include <linux/swap.h>
17 #include <linux/processor.h>
18 #include <linux/trace_events.h>
19 #include <asm/fpu/internal.h>
20 
21 #include <asm/trapnr.h>
22 
23 #include "x86.h"
24 #include "svm.h"
25 #include "svm_ops.h"
26 #include "cpuid.h"
27 #include "trace.h"
28 
29 #define __ex(x) __kvm_handle_fault_on_reboot(x)
30 
31 static u8 sev_enc_bit;
32 static int sev_flush_asids(void);
33 static DECLARE_RWSEM(sev_deactivate_lock);
34 static DEFINE_MUTEX(sev_bitmap_lock);
35 unsigned int max_sev_asid;
36 static unsigned int min_sev_asid;
37 static unsigned long *sev_asid_bitmap;
38 static unsigned long *sev_reclaim_asid_bitmap;
39 
40 struct enc_region {
41 	struct list_head list;
42 	unsigned long npages;
43 	struct page **pages;
44 	unsigned long uaddr;
45 	unsigned long size;
46 };
47 
48 static int sev_flush_asids(void)
49 {
50 	int ret, error = 0;
51 
52 	/*
53 	 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
54 	 * so it must be guarded.
55 	 */
56 	down_write(&sev_deactivate_lock);
57 
58 	wbinvd_on_all_cpus();
59 	ret = sev_guest_df_flush(&error);
60 
61 	up_write(&sev_deactivate_lock);
62 
63 	if (ret)
64 		pr_err("SEV: DF_FLUSH failed, ret=%d, error=%#x\n", ret, error);
65 
66 	return ret;
67 }
68 
69 /* Must be called with the sev_bitmap_lock held */
70 static bool __sev_recycle_asids(int min_asid, int max_asid)
71 {
72 	int pos;
73 
74 	/* Check if there are any ASIDs to reclaim before performing a flush */
75 	pos = find_next_bit(sev_reclaim_asid_bitmap, max_sev_asid, min_asid);
76 	if (pos >= max_asid)
77 		return false;
78 
79 	if (sev_flush_asids())
80 		return false;
81 
82 	/* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */
83 	bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
84 		   max_sev_asid);
85 	bitmap_zero(sev_reclaim_asid_bitmap, max_sev_asid);
86 
87 	return true;
88 }
89 
90 static int sev_asid_new(struct kvm_sev_info *sev)
91 {
92 	int pos, min_asid, max_asid;
93 	bool retry = true;
94 
95 	mutex_lock(&sev_bitmap_lock);
96 
97 	/*
98 	 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid.
99 	 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1.
100 	 */
101 	min_asid = sev->es_active ? 0 : min_sev_asid - 1;
102 	max_asid = sev->es_active ? min_sev_asid - 1 : max_sev_asid;
103 again:
104 	pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_asid);
105 	if (pos >= max_asid) {
106 		if (retry && __sev_recycle_asids(min_asid, max_asid)) {
107 			retry = false;
108 			goto again;
109 		}
110 		mutex_unlock(&sev_bitmap_lock);
111 		return -EBUSY;
112 	}
113 
114 	__set_bit(pos, sev_asid_bitmap);
115 
116 	mutex_unlock(&sev_bitmap_lock);
117 
118 	return pos + 1;
119 }
120 
121 static int sev_get_asid(struct kvm *kvm)
122 {
123 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
124 
125 	return sev->asid;
126 }
127 
128 static void sev_asid_free(int asid)
129 {
130 	struct svm_cpu_data *sd;
131 	int cpu, pos;
132 
133 	mutex_lock(&sev_bitmap_lock);
134 
135 	pos = asid - 1;
136 	__set_bit(pos, sev_reclaim_asid_bitmap);
137 
138 	for_each_possible_cpu(cpu) {
139 		sd = per_cpu(svm_data, cpu);
140 		sd->sev_vmcbs[pos] = NULL;
141 	}
142 
143 	mutex_unlock(&sev_bitmap_lock);
144 }
145 
146 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
147 {
148 	struct sev_data_decommission *decommission;
149 	struct sev_data_deactivate *data;
150 
151 	if (!handle)
152 		return;
153 
154 	data = kzalloc(sizeof(*data), GFP_KERNEL);
155 	if (!data)
156 		return;
157 
158 	/* deactivate handle */
159 	data->handle = handle;
160 
161 	/* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
162 	down_read(&sev_deactivate_lock);
163 	sev_guest_deactivate(data, NULL);
164 	up_read(&sev_deactivate_lock);
165 
166 	kfree(data);
167 
168 	decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
169 	if (!decommission)
170 		return;
171 
172 	/* decommission handle */
173 	decommission->handle = handle;
174 	sev_guest_decommission(decommission, NULL);
175 
176 	kfree(decommission);
177 }
178 
179 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
180 {
181 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
182 	int asid, ret;
183 
184 	ret = -EBUSY;
185 	if (unlikely(sev->active))
186 		return ret;
187 
188 	asid = sev_asid_new(sev);
189 	if (asid < 0)
190 		return ret;
191 
192 	ret = sev_platform_init(&argp->error);
193 	if (ret)
194 		goto e_free;
195 
196 	sev->active = true;
197 	sev->asid = asid;
198 	INIT_LIST_HEAD(&sev->regions_list);
199 
200 	return 0;
201 
202 e_free:
203 	sev_asid_free(asid);
204 	return ret;
205 }
206 
207 static int sev_es_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
208 {
209 	if (!sev_es)
210 		return -ENOTTY;
211 
212 	to_kvm_svm(kvm)->sev_info.es_active = true;
213 
214 	return sev_guest_init(kvm, argp);
215 }
216 
217 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
218 {
219 	struct sev_data_activate *data;
220 	int asid = sev_get_asid(kvm);
221 	int ret;
222 
223 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
224 	if (!data)
225 		return -ENOMEM;
226 
227 	/* activate ASID on the given handle */
228 	data->handle = handle;
229 	data->asid   = asid;
230 	ret = sev_guest_activate(data, error);
231 	kfree(data);
232 
233 	return ret;
234 }
235 
236 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
237 {
238 	struct fd f;
239 	int ret;
240 
241 	f = fdget(fd);
242 	if (!f.file)
243 		return -EBADF;
244 
245 	ret = sev_issue_cmd_external_user(f.file, id, data, error);
246 
247 	fdput(f);
248 	return ret;
249 }
250 
251 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
252 {
253 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
254 
255 	return __sev_issue_cmd(sev->fd, id, data, error);
256 }
257 
258 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
259 {
260 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
261 	struct sev_data_launch_start *start;
262 	struct kvm_sev_launch_start params;
263 	void *dh_blob, *session_blob;
264 	int *error = &argp->error;
265 	int ret;
266 
267 	if (!sev_guest(kvm))
268 		return -ENOTTY;
269 
270 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
271 		return -EFAULT;
272 
273 	start = kzalloc(sizeof(*start), GFP_KERNEL_ACCOUNT);
274 	if (!start)
275 		return -ENOMEM;
276 
277 	dh_blob = NULL;
278 	if (params.dh_uaddr) {
279 		dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
280 		if (IS_ERR(dh_blob)) {
281 			ret = PTR_ERR(dh_blob);
282 			goto e_free;
283 		}
284 
285 		start->dh_cert_address = __sme_set(__pa(dh_blob));
286 		start->dh_cert_len = params.dh_len;
287 	}
288 
289 	session_blob = NULL;
290 	if (params.session_uaddr) {
291 		session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
292 		if (IS_ERR(session_blob)) {
293 			ret = PTR_ERR(session_blob);
294 			goto e_free_dh;
295 		}
296 
297 		start->session_address = __sme_set(__pa(session_blob));
298 		start->session_len = params.session_len;
299 	}
300 
301 	start->handle = params.handle;
302 	start->policy = params.policy;
303 
304 	/* create memory encryption context */
305 	ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
306 	if (ret)
307 		goto e_free_session;
308 
309 	/* Bind ASID to this guest */
310 	ret = sev_bind_asid(kvm, start->handle, error);
311 	if (ret)
312 		goto e_free_session;
313 
314 	/* return handle to userspace */
315 	params.handle = start->handle;
316 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params))) {
317 		sev_unbind_asid(kvm, start->handle);
318 		ret = -EFAULT;
319 		goto e_free_session;
320 	}
321 
322 	sev->handle = start->handle;
323 	sev->fd = argp->sev_fd;
324 
325 e_free_session:
326 	kfree(session_blob);
327 e_free_dh:
328 	kfree(dh_blob);
329 e_free:
330 	kfree(start);
331 	return ret;
332 }
333 
334 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
335 				    unsigned long ulen, unsigned long *n,
336 				    int write)
337 {
338 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
339 	unsigned long npages, size;
340 	int npinned;
341 	unsigned long locked, lock_limit;
342 	struct page **pages;
343 	unsigned long first, last;
344 	int ret;
345 
346 	lockdep_assert_held(&kvm->lock);
347 
348 	if (ulen == 0 || uaddr + ulen < uaddr)
349 		return ERR_PTR(-EINVAL);
350 
351 	/* Calculate number of pages. */
352 	first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
353 	last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
354 	npages = (last - first + 1);
355 
356 	locked = sev->pages_locked + npages;
357 	lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
358 	if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
359 		pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
360 		return ERR_PTR(-ENOMEM);
361 	}
362 
363 	if (WARN_ON_ONCE(npages > INT_MAX))
364 		return ERR_PTR(-EINVAL);
365 
366 	/* Avoid using vmalloc for smaller buffers. */
367 	size = npages * sizeof(struct page *);
368 	if (size > PAGE_SIZE)
369 		pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
370 	else
371 		pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
372 
373 	if (!pages)
374 		return ERR_PTR(-ENOMEM);
375 
376 	/* Pin the user virtual address. */
377 	npinned = pin_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
378 	if (npinned != npages) {
379 		pr_err("SEV: Failure locking %lu pages.\n", npages);
380 		ret = -ENOMEM;
381 		goto err;
382 	}
383 
384 	*n = npages;
385 	sev->pages_locked = locked;
386 
387 	return pages;
388 
389 err:
390 	if (npinned > 0)
391 		unpin_user_pages(pages, npinned);
392 
393 	kvfree(pages);
394 	return ERR_PTR(ret);
395 }
396 
397 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
398 			     unsigned long npages)
399 {
400 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
401 
402 	unpin_user_pages(pages, npages);
403 	kvfree(pages);
404 	sev->pages_locked -= npages;
405 }
406 
407 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
408 {
409 	uint8_t *page_virtual;
410 	unsigned long i;
411 
412 	if (this_cpu_has(X86_FEATURE_SME_COHERENT) || npages == 0 ||
413 	    pages == NULL)
414 		return;
415 
416 	for (i = 0; i < npages; i++) {
417 		page_virtual = kmap_atomic(pages[i]);
418 		clflush_cache_range(page_virtual, PAGE_SIZE);
419 		kunmap_atomic(page_virtual);
420 	}
421 }
422 
423 static unsigned long get_num_contig_pages(unsigned long idx,
424 				struct page **inpages, unsigned long npages)
425 {
426 	unsigned long paddr, next_paddr;
427 	unsigned long i = idx + 1, pages = 1;
428 
429 	/* find the number of contiguous pages starting from idx */
430 	paddr = __sme_page_pa(inpages[idx]);
431 	while (i < npages) {
432 		next_paddr = __sme_page_pa(inpages[i++]);
433 		if ((paddr + PAGE_SIZE) == next_paddr) {
434 			pages++;
435 			paddr = next_paddr;
436 			continue;
437 		}
438 		break;
439 	}
440 
441 	return pages;
442 }
443 
444 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
445 {
446 	unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
447 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
448 	struct kvm_sev_launch_update_data params;
449 	struct sev_data_launch_update_data *data;
450 	struct page **inpages;
451 	int ret;
452 
453 	if (!sev_guest(kvm))
454 		return -ENOTTY;
455 
456 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
457 		return -EFAULT;
458 
459 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
460 	if (!data)
461 		return -ENOMEM;
462 
463 	vaddr = params.uaddr;
464 	size = params.len;
465 	vaddr_end = vaddr + size;
466 
467 	/* Lock the user memory. */
468 	inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
469 	if (IS_ERR(inpages)) {
470 		ret = PTR_ERR(inpages);
471 		goto e_free;
472 	}
473 
474 	/*
475 	 * Flush (on non-coherent CPUs) before LAUNCH_UPDATE encrypts pages in
476 	 * place; the cache may contain the data that was written unencrypted.
477 	 */
478 	sev_clflush_pages(inpages, npages);
479 
480 	for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
481 		int offset, len;
482 
483 		/*
484 		 * If the user buffer is not page-aligned, calculate the offset
485 		 * within the page.
486 		 */
487 		offset = vaddr & (PAGE_SIZE - 1);
488 
489 		/* Calculate the number of pages that can be encrypted in one go. */
490 		pages = get_num_contig_pages(i, inpages, npages);
491 
492 		len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
493 
494 		data->handle = sev->handle;
495 		data->len = len;
496 		data->address = __sme_page_pa(inpages[i]) + offset;
497 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
498 		if (ret)
499 			goto e_unpin;
500 
501 		size -= len;
502 		next_vaddr = vaddr + len;
503 	}
504 
505 e_unpin:
506 	/* content of memory is updated, mark pages dirty */
507 	for (i = 0; i < npages; i++) {
508 		set_page_dirty_lock(inpages[i]);
509 		mark_page_accessed(inpages[i]);
510 	}
511 	/* unlock the user pages */
512 	sev_unpin_memory(kvm, inpages, npages);
513 e_free:
514 	kfree(data);
515 	return ret;
516 }
517 
518 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
519 {
520 	struct vmcb_save_area *save = &svm->vmcb->save;
521 
522 	/* Check some debug related fields before encrypting the VMSA */
523 	if (svm->vcpu.guest_debug || (save->dr7 & ~DR7_FIXED_1))
524 		return -EINVAL;
525 
526 	/* Sync registgers */
527 	save->rax = svm->vcpu.arch.regs[VCPU_REGS_RAX];
528 	save->rbx = svm->vcpu.arch.regs[VCPU_REGS_RBX];
529 	save->rcx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
530 	save->rdx = svm->vcpu.arch.regs[VCPU_REGS_RDX];
531 	save->rsp = svm->vcpu.arch.regs[VCPU_REGS_RSP];
532 	save->rbp = svm->vcpu.arch.regs[VCPU_REGS_RBP];
533 	save->rsi = svm->vcpu.arch.regs[VCPU_REGS_RSI];
534 	save->rdi = svm->vcpu.arch.regs[VCPU_REGS_RDI];
535 #ifdef CONFIG_X86_64
536 	save->r8  = svm->vcpu.arch.regs[VCPU_REGS_R8];
537 	save->r9  = svm->vcpu.arch.regs[VCPU_REGS_R9];
538 	save->r10 = svm->vcpu.arch.regs[VCPU_REGS_R10];
539 	save->r11 = svm->vcpu.arch.regs[VCPU_REGS_R11];
540 	save->r12 = svm->vcpu.arch.regs[VCPU_REGS_R12];
541 	save->r13 = svm->vcpu.arch.regs[VCPU_REGS_R13];
542 	save->r14 = svm->vcpu.arch.regs[VCPU_REGS_R14];
543 	save->r15 = svm->vcpu.arch.regs[VCPU_REGS_R15];
544 #endif
545 	save->rip = svm->vcpu.arch.regs[VCPU_REGS_RIP];
546 
547 	/* Sync some non-GPR registers before encrypting */
548 	save->xcr0 = svm->vcpu.arch.xcr0;
549 	save->pkru = svm->vcpu.arch.pkru;
550 	save->xss  = svm->vcpu.arch.ia32_xss;
551 
552 	/*
553 	 * SEV-ES will use a VMSA that is pointed to by the VMCB, not
554 	 * the traditional VMSA that is part of the VMCB. Copy the
555 	 * traditional VMSA as it has been built so far (in prep
556 	 * for LAUNCH_UPDATE_VMSA) to be the initial SEV-ES state.
557 	 */
558 	memcpy(svm->vmsa, save, sizeof(*save));
559 
560 	return 0;
561 }
562 
563 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
564 {
565 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
566 	struct sev_data_launch_update_vmsa *vmsa;
567 	int i, ret;
568 
569 	if (!sev_es_guest(kvm))
570 		return -ENOTTY;
571 
572 	vmsa = kzalloc(sizeof(*vmsa), GFP_KERNEL);
573 	if (!vmsa)
574 		return -ENOMEM;
575 
576 	for (i = 0; i < kvm->created_vcpus; i++) {
577 		struct vcpu_svm *svm = to_svm(kvm->vcpus[i]);
578 
579 		/* Perform some pre-encryption checks against the VMSA */
580 		ret = sev_es_sync_vmsa(svm);
581 		if (ret)
582 			goto e_free;
583 
584 		/*
585 		 * The LAUNCH_UPDATE_VMSA command will perform in-place
586 		 * encryption of the VMSA memory content (i.e it will write
587 		 * the same memory region with the guest's key), so invalidate
588 		 * it first.
589 		 */
590 		clflush_cache_range(svm->vmsa, PAGE_SIZE);
591 
592 		vmsa->handle = sev->handle;
593 		vmsa->address = __sme_pa(svm->vmsa);
594 		vmsa->len = PAGE_SIZE;
595 		ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_VMSA, vmsa,
596 				    &argp->error);
597 		if (ret)
598 			goto e_free;
599 
600 		svm->vcpu.arch.guest_state_protected = true;
601 	}
602 
603 e_free:
604 	kfree(vmsa);
605 	return ret;
606 }
607 
608 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
609 {
610 	void __user *measure = (void __user *)(uintptr_t)argp->data;
611 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
612 	struct sev_data_launch_measure *data;
613 	struct kvm_sev_launch_measure params;
614 	void __user *p = NULL;
615 	void *blob = NULL;
616 	int ret;
617 
618 	if (!sev_guest(kvm))
619 		return -ENOTTY;
620 
621 	if (copy_from_user(&params, measure, sizeof(params)))
622 		return -EFAULT;
623 
624 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
625 	if (!data)
626 		return -ENOMEM;
627 
628 	/* User wants to query the blob length */
629 	if (!params.len)
630 		goto cmd;
631 
632 	p = (void __user *)(uintptr_t)params.uaddr;
633 	if (p) {
634 		if (params.len > SEV_FW_BLOB_MAX_SIZE) {
635 			ret = -EINVAL;
636 			goto e_free;
637 		}
638 
639 		ret = -ENOMEM;
640 		blob = kmalloc(params.len, GFP_KERNEL);
641 		if (!blob)
642 			goto e_free;
643 
644 		data->address = __psp_pa(blob);
645 		data->len = params.len;
646 	}
647 
648 cmd:
649 	data->handle = sev->handle;
650 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
651 
652 	/*
653 	 * If we query the session length, FW responded with expected data.
654 	 */
655 	if (!params.len)
656 		goto done;
657 
658 	if (ret)
659 		goto e_free_blob;
660 
661 	if (blob) {
662 		if (copy_to_user(p, blob, params.len))
663 			ret = -EFAULT;
664 	}
665 
666 done:
667 	params.len = data->len;
668 	if (copy_to_user(measure, &params, sizeof(params)))
669 		ret = -EFAULT;
670 e_free_blob:
671 	kfree(blob);
672 e_free:
673 	kfree(data);
674 	return ret;
675 }
676 
677 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
678 {
679 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
680 	struct sev_data_launch_finish *data;
681 	int ret;
682 
683 	if (!sev_guest(kvm))
684 		return -ENOTTY;
685 
686 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
687 	if (!data)
688 		return -ENOMEM;
689 
690 	data->handle = sev->handle;
691 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
692 
693 	kfree(data);
694 	return ret;
695 }
696 
697 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
698 {
699 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
700 	struct kvm_sev_guest_status params;
701 	struct sev_data_guest_status *data;
702 	int ret;
703 
704 	if (!sev_guest(kvm))
705 		return -ENOTTY;
706 
707 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
708 	if (!data)
709 		return -ENOMEM;
710 
711 	data->handle = sev->handle;
712 	ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
713 	if (ret)
714 		goto e_free;
715 
716 	params.policy = data->policy;
717 	params.state = data->state;
718 	params.handle = data->handle;
719 
720 	if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
721 		ret = -EFAULT;
722 e_free:
723 	kfree(data);
724 	return ret;
725 }
726 
727 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
728 			       unsigned long dst, int size,
729 			       int *error, bool enc)
730 {
731 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
732 	struct sev_data_dbg *data;
733 	int ret;
734 
735 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
736 	if (!data)
737 		return -ENOMEM;
738 
739 	data->handle = sev->handle;
740 	data->dst_addr = dst;
741 	data->src_addr = src;
742 	data->len = size;
743 
744 	ret = sev_issue_cmd(kvm,
745 			    enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
746 			    data, error);
747 	kfree(data);
748 	return ret;
749 }
750 
751 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
752 			     unsigned long dst_paddr, int sz, int *err)
753 {
754 	int offset;
755 
756 	/*
757 	 * Its safe to read more than we are asked, caller should ensure that
758 	 * destination has enough space.
759 	 */
760 	offset = src_paddr & 15;
761 	src_paddr = round_down(src_paddr, 16);
762 	sz = round_up(sz + offset, 16);
763 
764 	return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
765 }
766 
767 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
768 				  unsigned long __user dst_uaddr,
769 				  unsigned long dst_paddr,
770 				  int size, int *err)
771 {
772 	struct page *tpage = NULL;
773 	int ret, offset;
774 
775 	/* if inputs are not 16-byte then use intermediate buffer */
776 	if (!IS_ALIGNED(dst_paddr, 16) ||
777 	    !IS_ALIGNED(paddr,     16) ||
778 	    !IS_ALIGNED(size,      16)) {
779 		tpage = (void *)alloc_page(GFP_KERNEL);
780 		if (!tpage)
781 			return -ENOMEM;
782 
783 		dst_paddr = __sme_page_pa(tpage);
784 	}
785 
786 	ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
787 	if (ret)
788 		goto e_free;
789 
790 	if (tpage) {
791 		offset = paddr & 15;
792 		if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
793 				 page_address(tpage) + offset, size))
794 			ret = -EFAULT;
795 	}
796 
797 e_free:
798 	if (tpage)
799 		__free_page(tpage);
800 
801 	return ret;
802 }
803 
804 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
805 				  unsigned long __user vaddr,
806 				  unsigned long dst_paddr,
807 				  unsigned long __user dst_vaddr,
808 				  int size, int *error)
809 {
810 	struct page *src_tpage = NULL;
811 	struct page *dst_tpage = NULL;
812 	int ret, len = size;
813 
814 	/* If source buffer is not aligned then use an intermediate buffer */
815 	if (!IS_ALIGNED(vaddr, 16)) {
816 		src_tpage = alloc_page(GFP_KERNEL);
817 		if (!src_tpage)
818 			return -ENOMEM;
819 
820 		if (copy_from_user(page_address(src_tpage),
821 				(void __user *)(uintptr_t)vaddr, size)) {
822 			__free_page(src_tpage);
823 			return -EFAULT;
824 		}
825 
826 		paddr = __sme_page_pa(src_tpage);
827 	}
828 
829 	/*
830 	 *  If destination buffer or length is not aligned then do read-modify-write:
831 	 *   - decrypt destination in an intermediate buffer
832 	 *   - copy the source buffer in an intermediate buffer
833 	 *   - use the intermediate buffer as source buffer
834 	 */
835 	if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
836 		int dst_offset;
837 
838 		dst_tpage = alloc_page(GFP_KERNEL);
839 		if (!dst_tpage) {
840 			ret = -ENOMEM;
841 			goto e_free;
842 		}
843 
844 		ret = __sev_dbg_decrypt(kvm, dst_paddr,
845 					__sme_page_pa(dst_tpage), size, error);
846 		if (ret)
847 			goto e_free;
848 
849 		/*
850 		 *  If source is kernel buffer then use memcpy() otherwise
851 		 *  copy_from_user().
852 		 */
853 		dst_offset = dst_paddr & 15;
854 
855 		if (src_tpage)
856 			memcpy(page_address(dst_tpage) + dst_offset,
857 			       page_address(src_tpage), size);
858 		else {
859 			if (copy_from_user(page_address(dst_tpage) + dst_offset,
860 					   (void __user *)(uintptr_t)vaddr, size)) {
861 				ret = -EFAULT;
862 				goto e_free;
863 			}
864 		}
865 
866 		paddr = __sme_page_pa(dst_tpage);
867 		dst_paddr = round_down(dst_paddr, 16);
868 		len = round_up(size, 16);
869 	}
870 
871 	ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
872 
873 e_free:
874 	if (src_tpage)
875 		__free_page(src_tpage);
876 	if (dst_tpage)
877 		__free_page(dst_tpage);
878 	return ret;
879 }
880 
881 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
882 {
883 	unsigned long vaddr, vaddr_end, next_vaddr;
884 	unsigned long dst_vaddr;
885 	struct page **src_p, **dst_p;
886 	struct kvm_sev_dbg debug;
887 	unsigned long n;
888 	unsigned int size;
889 	int ret;
890 
891 	if (!sev_guest(kvm))
892 		return -ENOTTY;
893 
894 	if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
895 		return -EFAULT;
896 
897 	if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
898 		return -EINVAL;
899 	if (!debug.dst_uaddr)
900 		return -EINVAL;
901 
902 	vaddr = debug.src_uaddr;
903 	size = debug.len;
904 	vaddr_end = vaddr + size;
905 	dst_vaddr = debug.dst_uaddr;
906 
907 	for (; vaddr < vaddr_end; vaddr = next_vaddr) {
908 		int len, s_off, d_off;
909 
910 		/* lock userspace source and destination page */
911 		src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
912 		if (IS_ERR(src_p))
913 			return PTR_ERR(src_p);
914 
915 		dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
916 		if (IS_ERR(dst_p)) {
917 			sev_unpin_memory(kvm, src_p, n);
918 			return PTR_ERR(dst_p);
919 		}
920 
921 		/*
922 		 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify
923 		 * the pages; flush the destination too so that future accesses do not
924 		 * see stale data.
925 		 */
926 		sev_clflush_pages(src_p, 1);
927 		sev_clflush_pages(dst_p, 1);
928 
929 		/*
930 		 * Since user buffer may not be page aligned, calculate the
931 		 * offset within the page.
932 		 */
933 		s_off = vaddr & ~PAGE_MASK;
934 		d_off = dst_vaddr & ~PAGE_MASK;
935 		len = min_t(size_t, (PAGE_SIZE - s_off), size);
936 
937 		if (dec)
938 			ret = __sev_dbg_decrypt_user(kvm,
939 						     __sme_page_pa(src_p[0]) + s_off,
940 						     dst_vaddr,
941 						     __sme_page_pa(dst_p[0]) + d_off,
942 						     len, &argp->error);
943 		else
944 			ret = __sev_dbg_encrypt_user(kvm,
945 						     __sme_page_pa(src_p[0]) + s_off,
946 						     vaddr,
947 						     __sme_page_pa(dst_p[0]) + d_off,
948 						     dst_vaddr,
949 						     len, &argp->error);
950 
951 		sev_unpin_memory(kvm, src_p, n);
952 		sev_unpin_memory(kvm, dst_p, n);
953 
954 		if (ret)
955 			goto err;
956 
957 		next_vaddr = vaddr + len;
958 		dst_vaddr = dst_vaddr + len;
959 		size -= len;
960 	}
961 err:
962 	return ret;
963 }
964 
965 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
966 {
967 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
968 	struct sev_data_launch_secret *data;
969 	struct kvm_sev_launch_secret params;
970 	struct page **pages;
971 	void *blob, *hdr;
972 	unsigned long n, i;
973 	int ret, offset;
974 
975 	if (!sev_guest(kvm))
976 		return -ENOTTY;
977 
978 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
979 		return -EFAULT;
980 
981 	pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
982 	if (IS_ERR(pages))
983 		return PTR_ERR(pages);
984 
985 	/*
986 	 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in
987 	 * place; the cache may contain the data that was written unencrypted.
988 	 */
989 	sev_clflush_pages(pages, n);
990 
991 	/*
992 	 * The secret must be copied into contiguous memory region, lets verify
993 	 * that userspace memory pages are contiguous before we issue command.
994 	 */
995 	if (get_num_contig_pages(0, pages, n) != n) {
996 		ret = -EINVAL;
997 		goto e_unpin_memory;
998 	}
999 
1000 	ret = -ENOMEM;
1001 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
1002 	if (!data)
1003 		goto e_unpin_memory;
1004 
1005 	offset = params.guest_uaddr & (PAGE_SIZE - 1);
1006 	data->guest_address = __sme_page_pa(pages[0]) + offset;
1007 	data->guest_len = params.guest_len;
1008 
1009 	blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1010 	if (IS_ERR(blob)) {
1011 		ret = PTR_ERR(blob);
1012 		goto e_free;
1013 	}
1014 
1015 	data->trans_address = __psp_pa(blob);
1016 	data->trans_len = params.trans_len;
1017 
1018 	hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1019 	if (IS_ERR(hdr)) {
1020 		ret = PTR_ERR(hdr);
1021 		goto e_free_blob;
1022 	}
1023 	data->hdr_address = __psp_pa(hdr);
1024 	data->hdr_len = params.hdr_len;
1025 
1026 	data->handle = sev->handle;
1027 	ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
1028 
1029 	kfree(hdr);
1030 
1031 e_free_blob:
1032 	kfree(blob);
1033 e_free:
1034 	kfree(data);
1035 e_unpin_memory:
1036 	/* content of memory is updated, mark pages dirty */
1037 	for (i = 0; i < n; i++) {
1038 		set_page_dirty_lock(pages[i]);
1039 		mark_page_accessed(pages[i]);
1040 	}
1041 	sev_unpin_memory(kvm, pages, n);
1042 	return ret;
1043 }
1044 
1045 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp)
1046 {
1047 	void __user *report = (void __user *)(uintptr_t)argp->data;
1048 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1049 	struct sev_data_attestation_report *data;
1050 	struct kvm_sev_attestation_report params;
1051 	void __user *p;
1052 	void *blob = NULL;
1053 	int ret;
1054 
1055 	if (!sev_guest(kvm))
1056 		return -ENOTTY;
1057 
1058 	if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
1059 		return -EFAULT;
1060 
1061 	data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
1062 	if (!data)
1063 		return -ENOMEM;
1064 
1065 	/* User wants to query the blob length */
1066 	if (!params.len)
1067 		goto cmd;
1068 
1069 	p = (void __user *)(uintptr_t)params.uaddr;
1070 	if (p) {
1071 		if (params.len > SEV_FW_BLOB_MAX_SIZE) {
1072 			ret = -EINVAL;
1073 			goto e_free;
1074 		}
1075 
1076 		ret = -ENOMEM;
1077 		blob = kmalloc(params.len, GFP_KERNEL);
1078 		if (!blob)
1079 			goto e_free;
1080 
1081 		data->address = __psp_pa(blob);
1082 		data->len = params.len;
1083 		memcpy(data->mnonce, params.mnonce, sizeof(params.mnonce));
1084 	}
1085 cmd:
1086 	data->handle = sev->handle;
1087 	ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, data, &argp->error);
1088 	/*
1089 	 * If we query the session length, FW responded with expected data.
1090 	 */
1091 	if (!params.len)
1092 		goto done;
1093 
1094 	if (ret)
1095 		goto e_free_blob;
1096 
1097 	if (blob) {
1098 		if (copy_to_user(p, blob, params.len))
1099 			ret = -EFAULT;
1100 	}
1101 
1102 done:
1103 	params.len = data->len;
1104 	if (copy_to_user(report, &params, sizeof(params)))
1105 		ret = -EFAULT;
1106 e_free_blob:
1107 	kfree(blob);
1108 e_free:
1109 	kfree(data);
1110 	return ret;
1111 }
1112 
1113 int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
1114 {
1115 	struct kvm_sev_cmd sev_cmd;
1116 	int r;
1117 
1118 	if (!svm_sev_enabled() || !sev)
1119 		return -ENOTTY;
1120 
1121 	if (!argp)
1122 		return 0;
1123 
1124 	if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
1125 		return -EFAULT;
1126 
1127 	mutex_lock(&kvm->lock);
1128 
1129 	switch (sev_cmd.id) {
1130 	case KVM_SEV_INIT:
1131 		r = sev_guest_init(kvm, &sev_cmd);
1132 		break;
1133 	case KVM_SEV_ES_INIT:
1134 		r = sev_es_guest_init(kvm, &sev_cmd);
1135 		break;
1136 	case KVM_SEV_LAUNCH_START:
1137 		r = sev_launch_start(kvm, &sev_cmd);
1138 		break;
1139 	case KVM_SEV_LAUNCH_UPDATE_DATA:
1140 		r = sev_launch_update_data(kvm, &sev_cmd);
1141 		break;
1142 	case KVM_SEV_LAUNCH_UPDATE_VMSA:
1143 		r = sev_launch_update_vmsa(kvm, &sev_cmd);
1144 		break;
1145 	case KVM_SEV_LAUNCH_MEASURE:
1146 		r = sev_launch_measure(kvm, &sev_cmd);
1147 		break;
1148 	case KVM_SEV_LAUNCH_FINISH:
1149 		r = sev_launch_finish(kvm, &sev_cmd);
1150 		break;
1151 	case KVM_SEV_GUEST_STATUS:
1152 		r = sev_guest_status(kvm, &sev_cmd);
1153 		break;
1154 	case KVM_SEV_DBG_DECRYPT:
1155 		r = sev_dbg_crypt(kvm, &sev_cmd, true);
1156 		break;
1157 	case KVM_SEV_DBG_ENCRYPT:
1158 		r = sev_dbg_crypt(kvm, &sev_cmd, false);
1159 		break;
1160 	case KVM_SEV_LAUNCH_SECRET:
1161 		r = sev_launch_secret(kvm, &sev_cmd);
1162 		break;
1163 	case KVM_SEV_GET_ATTESTATION_REPORT:
1164 		r = sev_get_attestation_report(kvm, &sev_cmd);
1165 		break;
1166 	default:
1167 		r = -EINVAL;
1168 		goto out;
1169 	}
1170 
1171 	if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
1172 		r = -EFAULT;
1173 
1174 out:
1175 	mutex_unlock(&kvm->lock);
1176 	return r;
1177 }
1178 
1179 int svm_register_enc_region(struct kvm *kvm,
1180 			    struct kvm_enc_region *range)
1181 {
1182 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1183 	struct enc_region *region;
1184 	int ret = 0;
1185 
1186 	if (!sev_guest(kvm))
1187 		return -ENOTTY;
1188 
1189 	if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
1190 		return -EINVAL;
1191 
1192 	region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
1193 	if (!region)
1194 		return -ENOMEM;
1195 
1196 	mutex_lock(&kvm->lock);
1197 	region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
1198 	if (IS_ERR(region->pages)) {
1199 		ret = PTR_ERR(region->pages);
1200 		mutex_unlock(&kvm->lock);
1201 		goto e_free;
1202 	}
1203 
1204 	region->uaddr = range->addr;
1205 	region->size = range->size;
1206 
1207 	list_add_tail(&region->list, &sev->regions_list);
1208 	mutex_unlock(&kvm->lock);
1209 
1210 	/*
1211 	 * The guest may change the memory encryption attribute from C=0 -> C=1
1212 	 * or vice versa for this memory range. Lets make sure caches are
1213 	 * flushed to ensure that guest data gets written into memory with
1214 	 * correct C-bit.
1215 	 */
1216 	sev_clflush_pages(region->pages, region->npages);
1217 
1218 	return ret;
1219 
1220 e_free:
1221 	kfree(region);
1222 	return ret;
1223 }
1224 
1225 static struct enc_region *
1226 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
1227 {
1228 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1229 	struct list_head *head = &sev->regions_list;
1230 	struct enc_region *i;
1231 
1232 	list_for_each_entry(i, head, list) {
1233 		if (i->uaddr == range->addr &&
1234 		    i->size == range->size)
1235 			return i;
1236 	}
1237 
1238 	return NULL;
1239 }
1240 
1241 static void __unregister_enc_region_locked(struct kvm *kvm,
1242 					   struct enc_region *region)
1243 {
1244 	sev_unpin_memory(kvm, region->pages, region->npages);
1245 	list_del(&region->list);
1246 	kfree(region);
1247 }
1248 
1249 int svm_unregister_enc_region(struct kvm *kvm,
1250 			      struct kvm_enc_region *range)
1251 {
1252 	struct enc_region *region;
1253 	int ret;
1254 
1255 	mutex_lock(&kvm->lock);
1256 
1257 	if (!sev_guest(kvm)) {
1258 		ret = -ENOTTY;
1259 		goto failed;
1260 	}
1261 
1262 	region = find_enc_region(kvm, range);
1263 	if (!region) {
1264 		ret = -EINVAL;
1265 		goto failed;
1266 	}
1267 
1268 	/*
1269 	 * Ensure that all guest tagged cache entries are flushed before
1270 	 * releasing the pages back to the system for use. CLFLUSH will
1271 	 * not do this, so issue a WBINVD.
1272 	 */
1273 	wbinvd_on_all_cpus();
1274 
1275 	__unregister_enc_region_locked(kvm, region);
1276 
1277 	mutex_unlock(&kvm->lock);
1278 	return 0;
1279 
1280 failed:
1281 	mutex_unlock(&kvm->lock);
1282 	return ret;
1283 }
1284 
1285 void sev_vm_destroy(struct kvm *kvm)
1286 {
1287 	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1288 	struct list_head *head = &sev->regions_list;
1289 	struct list_head *pos, *q;
1290 
1291 	if (!sev_guest(kvm))
1292 		return;
1293 
1294 	mutex_lock(&kvm->lock);
1295 
1296 	/*
1297 	 * Ensure that all guest tagged cache entries are flushed before
1298 	 * releasing the pages back to the system for use. CLFLUSH will
1299 	 * not do this, so issue a WBINVD.
1300 	 */
1301 	wbinvd_on_all_cpus();
1302 
1303 	/*
1304 	 * if userspace was terminated before unregistering the memory regions
1305 	 * then lets unpin all the registered memory.
1306 	 */
1307 	if (!list_empty(head)) {
1308 		list_for_each_safe(pos, q, head) {
1309 			__unregister_enc_region_locked(kvm,
1310 				list_entry(pos, struct enc_region, list));
1311 			cond_resched();
1312 		}
1313 	}
1314 
1315 	mutex_unlock(&kvm->lock);
1316 
1317 	sev_unbind_asid(kvm, sev->handle);
1318 	sev_asid_free(sev->asid);
1319 }
1320 
1321 void __init sev_hardware_setup(void)
1322 {
1323 	unsigned int eax, ebx, ecx, edx;
1324 	bool sev_es_supported = false;
1325 	bool sev_supported = false;
1326 
1327 	/* Does the CPU support SEV? */
1328 	if (!boot_cpu_has(X86_FEATURE_SEV))
1329 		goto out;
1330 
1331 	/* Retrieve SEV CPUID information */
1332 	cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
1333 
1334 	/* Set encryption bit location for SEV-ES guests */
1335 	sev_enc_bit = ebx & 0x3f;
1336 
1337 	/* Maximum number of encrypted guests supported simultaneously */
1338 	max_sev_asid = ecx;
1339 
1340 	if (!svm_sev_enabled())
1341 		goto out;
1342 
1343 	/* Minimum ASID value that should be used for SEV guest */
1344 	min_sev_asid = edx;
1345 
1346 	/* Initialize SEV ASID bitmaps */
1347 	sev_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1348 	if (!sev_asid_bitmap)
1349 		goto out;
1350 
1351 	sev_reclaim_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1352 	if (!sev_reclaim_asid_bitmap)
1353 		goto out;
1354 
1355 	pr_info("SEV supported: %u ASIDs\n", max_sev_asid - min_sev_asid + 1);
1356 	sev_supported = true;
1357 
1358 	/* SEV-ES support requested? */
1359 	if (!sev_es)
1360 		goto out;
1361 
1362 	/* Does the CPU support SEV-ES? */
1363 	if (!boot_cpu_has(X86_FEATURE_SEV_ES))
1364 		goto out;
1365 
1366 	/* Has the system been allocated ASIDs for SEV-ES? */
1367 	if (min_sev_asid == 1)
1368 		goto out;
1369 
1370 	pr_info("SEV-ES supported: %u ASIDs\n", min_sev_asid - 1);
1371 	sev_es_supported = true;
1372 
1373 out:
1374 	sev = sev_supported;
1375 	sev_es = sev_es_supported;
1376 }
1377 
1378 void sev_hardware_teardown(void)
1379 {
1380 	if (!svm_sev_enabled())
1381 		return;
1382 
1383 	bitmap_free(sev_asid_bitmap);
1384 	bitmap_free(sev_reclaim_asid_bitmap);
1385 
1386 	sev_flush_asids();
1387 }
1388 
1389 /*
1390  * Pages used by hardware to hold guest encrypted state must be flushed before
1391  * returning them to the system.
1392  */
1393 static void sev_flush_guest_memory(struct vcpu_svm *svm, void *va,
1394 				   unsigned long len)
1395 {
1396 	/*
1397 	 * If hardware enforced cache coherency for encrypted mappings of the
1398 	 * same physical page is supported, nothing to do.
1399 	 */
1400 	if (boot_cpu_has(X86_FEATURE_SME_COHERENT))
1401 		return;
1402 
1403 	/*
1404 	 * If the VM Page Flush MSR is supported, use it to flush the page
1405 	 * (using the page virtual address and the guest ASID).
1406 	 */
1407 	if (boot_cpu_has(X86_FEATURE_VM_PAGE_FLUSH)) {
1408 		struct kvm_sev_info *sev;
1409 		unsigned long va_start;
1410 		u64 start, stop;
1411 
1412 		/* Align start and stop to page boundaries. */
1413 		va_start = (unsigned long)va;
1414 		start = (u64)va_start & PAGE_MASK;
1415 		stop = PAGE_ALIGN((u64)va_start + len);
1416 
1417 		if (start < stop) {
1418 			sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
1419 
1420 			while (start < stop) {
1421 				wrmsrl(MSR_AMD64_VM_PAGE_FLUSH,
1422 				       start | sev->asid);
1423 
1424 				start += PAGE_SIZE;
1425 			}
1426 
1427 			return;
1428 		}
1429 
1430 		WARN(1, "Address overflow, using WBINVD\n");
1431 	}
1432 
1433 	/*
1434 	 * Hardware should always have one of the above features,
1435 	 * but if not, use WBINVD and issue a warning.
1436 	 */
1437 	WARN_ONCE(1, "Using WBINVD to flush guest memory\n");
1438 	wbinvd_on_all_cpus();
1439 }
1440 
1441 void sev_free_vcpu(struct kvm_vcpu *vcpu)
1442 {
1443 	struct vcpu_svm *svm;
1444 
1445 	if (!sev_es_guest(vcpu->kvm))
1446 		return;
1447 
1448 	svm = to_svm(vcpu);
1449 
1450 	if (vcpu->arch.guest_state_protected)
1451 		sev_flush_guest_memory(svm, svm->vmsa, PAGE_SIZE);
1452 	__free_page(virt_to_page(svm->vmsa));
1453 
1454 	if (svm->ghcb_sa_free)
1455 		kfree(svm->ghcb_sa);
1456 }
1457 
1458 static void dump_ghcb(struct vcpu_svm *svm)
1459 {
1460 	struct ghcb *ghcb = svm->ghcb;
1461 	unsigned int nbits;
1462 
1463 	/* Re-use the dump_invalid_vmcb module parameter */
1464 	if (!dump_invalid_vmcb) {
1465 		pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
1466 		return;
1467 	}
1468 
1469 	nbits = sizeof(ghcb->save.valid_bitmap) * 8;
1470 
1471 	pr_err("GHCB (GPA=%016llx):\n", svm->vmcb->control.ghcb_gpa);
1472 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
1473 	       ghcb->save.sw_exit_code, ghcb_sw_exit_code_is_valid(ghcb));
1474 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
1475 	       ghcb->save.sw_exit_info_1, ghcb_sw_exit_info_1_is_valid(ghcb));
1476 	pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
1477 	       ghcb->save.sw_exit_info_2, ghcb_sw_exit_info_2_is_valid(ghcb));
1478 	pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
1479 	       ghcb->save.sw_scratch, ghcb_sw_scratch_is_valid(ghcb));
1480 	pr_err("%-20s%*pb\n", "valid_bitmap", nbits, ghcb->save.valid_bitmap);
1481 }
1482 
1483 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
1484 {
1485 	struct kvm_vcpu *vcpu = &svm->vcpu;
1486 	struct ghcb *ghcb = svm->ghcb;
1487 
1488 	/*
1489 	 * The GHCB protocol so far allows for the following data
1490 	 * to be returned:
1491 	 *   GPRs RAX, RBX, RCX, RDX
1492 	 *
1493 	 * Copy their values, even if they may not have been written during the
1494 	 * VM-Exit.  It's the guest's responsibility to not consume random data.
1495 	 */
1496 	ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
1497 	ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
1498 	ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
1499 	ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
1500 }
1501 
1502 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
1503 {
1504 	struct vmcb_control_area *control = &svm->vmcb->control;
1505 	struct kvm_vcpu *vcpu = &svm->vcpu;
1506 	struct ghcb *ghcb = svm->ghcb;
1507 	u64 exit_code;
1508 
1509 	/*
1510 	 * The GHCB protocol so far allows for the following data
1511 	 * to be supplied:
1512 	 *   GPRs RAX, RBX, RCX, RDX
1513 	 *   XCR0
1514 	 *   CPL
1515 	 *
1516 	 * VMMCALL allows the guest to provide extra registers. KVM also
1517 	 * expects RSI for hypercalls, so include that, too.
1518 	 *
1519 	 * Copy their values to the appropriate location if supplied.
1520 	 */
1521 	memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
1522 
1523 	vcpu->arch.regs[VCPU_REGS_RAX] = ghcb_get_rax_if_valid(ghcb);
1524 	vcpu->arch.regs[VCPU_REGS_RBX] = ghcb_get_rbx_if_valid(ghcb);
1525 	vcpu->arch.regs[VCPU_REGS_RCX] = ghcb_get_rcx_if_valid(ghcb);
1526 	vcpu->arch.regs[VCPU_REGS_RDX] = ghcb_get_rdx_if_valid(ghcb);
1527 	vcpu->arch.regs[VCPU_REGS_RSI] = ghcb_get_rsi_if_valid(ghcb);
1528 
1529 	svm->vmcb->save.cpl = ghcb_get_cpl_if_valid(ghcb);
1530 
1531 	if (ghcb_xcr0_is_valid(ghcb)) {
1532 		vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb);
1533 		kvm_update_cpuid_runtime(vcpu);
1534 	}
1535 
1536 	/* Copy the GHCB exit information into the VMCB fields */
1537 	exit_code = ghcb_get_sw_exit_code(ghcb);
1538 	control->exit_code = lower_32_bits(exit_code);
1539 	control->exit_code_hi = upper_32_bits(exit_code);
1540 	control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb);
1541 	control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb);
1542 
1543 	/* Clear the valid entries fields */
1544 	memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
1545 }
1546 
1547 static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
1548 {
1549 	struct kvm_vcpu *vcpu;
1550 	struct ghcb *ghcb;
1551 	u64 exit_code = 0;
1552 
1553 	ghcb = svm->ghcb;
1554 
1555 	/* Only GHCB Usage code 0 is supported */
1556 	if (ghcb->ghcb_usage)
1557 		goto vmgexit_err;
1558 
1559 	/*
1560 	 * Retrieve the exit code now even though is may not be marked valid
1561 	 * as it could help with debugging.
1562 	 */
1563 	exit_code = ghcb_get_sw_exit_code(ghcb);
1564 
1565 	if (!ghcb_sw_exit_code_is_valid(ghcb) ||
1566 	    !ghcb_sw_exit_info_1_is_valid(ghcb) ||
1567 	    !ghcb_sw_exit_info_2_is_valid(ghcb))
1568 		goto vmgexit_err;
1569 
1570 	switch (ghcb_get_sw_exit_code(ghcb)) {
1571 	case SVM_EXIT_READ_DR7:
1572 		break;
1573 	case SVM_EXIT_WRITE_DR7:
1574 		if (!ghcb_rax_is_valid(ghcb))
1575 			goto vmgexit_err;
1576 		break;
1577 	case SVM_EXIT_RDTSC:
1578 		break;
1579 	case SVM_EXIT_RDPMC:
1580 		if (!ghcb_rcx_is_valid(ghcb))
1581 			goto vmgexit_err;
1582 		break;
1583 	case SVM_EXIT_CPUID:
1584 		if (!ghcb_rax_is_valid(ghcb) ||
1585 		    !ghcb_rcx_is_valid(ghcb))
1586 			goto vmgexit_err;
1587 		if (ghcb_get_rax(ghcb) == 0xd)
1588 			if (!ghcb_xcr0_is_valid(ghcb))
1589 				goto vmgexit_err;
1590 		break;
1591 	case SVM_EXIT_INVD:
1592 		break;
1593 	case SVM_EXIT_IOIO:
1594 		if (ghcb_get_sw_exit_info_1(ghcb) & SVM_IOIO_STR_MASK) {
1595 			if (!ghcb_sw_scratch_is_valid(ghcb))
1596 				goto vmgexit_err;
1597 		} else {
1598 			if (!(ghcb_get_sw_exit_info_1(ghcb) & SVM_IOIO_TYPE_MASK))
1599 				if (!ghcb_rax_is_valid(ghcb))
1600 					goto vmgexit_err;
1601 		}
1602 		break;
1603 	case SVM_EXIT_MSR:
1604 		if (!ghcb_rcx_is_valid(ghcb))
1605 			goto vmgexit_err;
1606 		if (ghcb_get_sw_exit_info_1(ghcb)) {
1607 			if (!ghcb_rax_is_valid(ghcb) ||
1608 			    !ghcb_rdx_is_valid(ghcb))
1609 				goto vmgexit_err;
1610 		}
1611 		break;
1612 	case SVM_EXIT_VMMCALL:
1613 		if (!ghcb_rax_is_valid(ghcb) ||
1614 		    !ghcb_cpl_is_valid(ghcb))
1615 			goto vmgexit_err;
1616 		break;
1617 	case SVM_EXIT_RDTSCP:
1618 		break;
1619 	case SVM_EXIT_WBINVD:
1620 		break;
1621 	case SVM_EXIT_MONITOR:
1622 		if (!ghcb_rax_is_valid(ghcb) ||
1623 		    !ghcb_rcx_is_valid(ghcb) ||
1624 		    !ghcb_rdx_is_valid(ghcb))
1625 			goto vmgexit_err;
1626 		break;
1627 	case SVM_EXIT_MWAIT:
1628 		if (!ghcb_rax_is_valid(ghcb) ||
1629 		    !ghcb_rcx_is_valid(ghcb))
1630 			goto vmgexit_err;
1631 		break;
1632 	case SVM_VMGEXIT_MMIO_READ:
1633 	case SVM_VMGEXIT_MMIO_WRITE:
1634 		if (!ghcb_sw_scratch_is_valid(ghcb))
1635 			goto vmgexit_err;
1636 		break;
1637 	case SVM_VMGEXIT_NMI_COMPLETE:
1638 	case SVM_VMGEXIT_AP_HLT_LOOP:
1639 	case SVM_VMGEXIT_AP_JUMP_TABLE:
1640 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
1641 		break;
1642 	default:
1643 		goto vmgexit_err;
1644 	}
1645 
1646 	return 0;
1647 
1648 vmgexit_err:
1649 	vcpu = &svm->vcpu;
1650 
1651 	if (ghcb->ghcb_usage) {
1652 		vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
1653 			    ghcb->ghcb_usage);
1654 	} else {
1655 		vcpu_unimpl(vcpu, "vmgexit: exit reason %#llx is not valid\n",
1656 			    exit_code);
1657 		dump_ghcb(svm);
1658 	}
1659 
1660 	vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
1661 	vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
1662 	vcpu->run->internal.ndata = 2;
1663 	vcpu->run->internal.data[0] = exit_code;
1664 	vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
1665 
1666 	return -EINVAL;
1667 }
1668 
1669 static void pre_sev_es_run(struct vcpu_svm *svm)
1670 {
1671 	if (!svm->ghcb)
1672 		return;
1673 
1674 	if (svm->ghcb_sa_free) {
1675 		/*
1676 		 * The scratch area lives outside the GHCB, so there is a
1677 		 * buffer that, depending on the operation performed, may
1678 		 * need to be synced, then freed.
1679 		 */
1680 		if (svm->ghcb_sa_sync) {
1681 			kvm_write_guest(svm->vcpu.kvm,
1682 					ghcb_get_sw_scratch(svm->ghcb),
1683 					svm->ghcb_sa, svm->ghcb_sa_len);
1684 			svm->ghcb_sa_sync = false;
1685 		}
1686 
1687 		kfree(svm->ghcb_sa);
1688 		svm->ghcb_sa = NULL;
1689 		svm->ghcb_sa_free = false;
1690 	}
1691 
1692 	trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->ghcb);
1693 
1694 	sev_es_sync_to_ghcb(svm);
1695 
1696 	kvm_vcpu_unmap(&svm->vcpu, &svm->ghcb_map, true);
1697 	svm->ghcb = NULL;
1698 }
1699 
1700 void pre_sev_run(struct vcpu_svm *svm, int cpu)
1701 {
1702 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1703 	int asid = sev_get_asid(svm->vcpu.kvm);
1704 
1705 	/* Perform any SEV-ES pre-run actions */
1706 	pre_sev_es_run(svm);
1707 
1708 	/* Assign the asid allocated with this SEV guest */
1709 	svm->asid = asid;
1710 
1711 	/*
1712 	 * Flush guest TLB:
1713 	 *
1714 	 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
1715 	 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
1716 	 */
1717 	if (sd->sev_vmcbs[asid] == svm->vmcb &&
1718 	    svm->vcpu.arch.last_vmentry_cpu == cpu)
1719 		return;
1720 
1721 	sd->sev_vmcbs[asid] = svm->vmcb;
1722 	svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
1723 	vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
1724 }
1725 
1726 #define GHCB_SCRATCH_AREA_LIMIT		(16ULL * PAGE_SIZE)
1727 static bool setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len)
1728 {
1729 	struct vmcb_control_area *control = &svm->vmcb->control;
1730 	struct ghcb *ghcb = svm->ghcb;
1731 	u64 ghcb_scratch_beg, ghcb_scratch_end;
1732 	u64 scratch_gpa_beg, scratch_gpa_end;
1733 	void *scratch_va;
1734 
1735 	scratch_gpa_beg = ghcb_get_sw_scratch(ghcb);
1736 	if (!scratch_gpa_beg) {
1737 		pr_err("vmgexit: scratch gpa not provided\n");
1738 		return false;
1739 	}
1740 
1741 	scratch_gpa_end = scratch_gpa_beg + len;
1742 	if (scratch_gpa_end < scratch_gpa_beg) {
1743 		pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
1744 		       len, scratch_gpa_beg);
1745 		return false;
1746 	}
1747 
1748 	if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
1749 		/* Scratch area begins within GHCB */
1750 		ghcb_scratch_beg = control->ghcb_gpa +
1751 				   offsetof(struct ghcb, shared_buffer);
1752 		ghcb_scratch_end = control->ghcb_gpa +
1753 				   offsetof(struct ghcb, reserved_1);
1754 
1755 		/*
1756 		 * If the scratch area begins within the GHCB, it must be
1757 		 * completely contained in the GHCB shared buffer area.
1758 		 */
1759 		if (scratch_gpa_beg < ghcb_scratch_beg ||
1760 		    scratch_gpa_end > ghcb_scratch_end) {
1761 			pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
1762 			       scratch_gpa_beg, scratch_gpa_end);
1763 			return false;
1764 		}
1765 
1766 		scratch_va = (void *)svm->ghcb;
1767 		scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
1768 	} else {
1769 		/*
1770 		 * The guest memory must be read into a kernel buffer, so
1771 		 * limit the size
1772 		 */
1773 		if (len > GHCB_SCRATCH_AREA_LIMIT) {
1774 			pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
1775 			       len, GHCB_SCRATCH_AREA_LIMIT);
1776 			return false;
1777 		}
1778 		scratch_va = kzalloc(len, GFP_KERNEL);
1779 		if (!scratch_va)
1780 			return false;
1781 
1782 		if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) {
1783 			/* Unable to copy scratch area from guest */
1784 			pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
1785 
1786 			kfree(scratch_va);
1787 			return false;
1788 		}
1789 
1790 		/*
1791 		 * The scratch area is outside the GHCB. The operation will
1792 		 * dictate whether the buffer needs to be synced before running
1793 		 * the vCPU next time (i.e. a read was requested so the data
1794 		 * must be written back to the guest memory).
1795 		 */
1796 		svm->ghcb_sa_sync = sync;
1797 		svm->ghcb_sa_free = true;
1798 	}
1799 
1800 	svm->ghcb_sa = scratch_va;
1801 	svm->ghcb_sa_len = len;
1802 
1803 	return true;
1804 }
1805 
1806 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
1807 			      unsigned int pos)
1808 {
1809 	svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
1810 	svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
1811 }
1812 
1813 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
1814 {
1815 	return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
1816 }
1817 
1818 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
1819 {
1820 	svm->vmcb->control.ghcb_gpa = value;
1821 }
1822 
1823 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
1824 {
1825 	struct vmcb_control_area *control = &svm->vmcb->control;
1826 	struct kvm_vcpu *vcpu = &svm->vcpu;
1827 	u64 ghcb_info;
1828 	int ret = 1;
1829 
1830 	ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
1831 
1832 	trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
1833 					     control->ghcb_gpa);
1834 
1835 	switch (ghcb_info) {
1836 	case GHCB_MSR_SEV_INFO_REQ:
1837 		set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
1838 						    GHCB_VERSION_MIN,
1839 						    sev_enc_bit));
1840 		break;
1841 	case GHCB_MSR_CPUID_REQ: {
1842 		u64 cpuid_fn, cpuid_reg, cpuid_value;
1843 
1844 		cpuid_fn = get_ghcb_msr_bits(svm,
1845 					     GHCB_MSR_CPUID_FUNC_MASK,
1846 					     GHCB_MSR_CPUID_FUNC_POS);
1847 
1848 		/* Initialize the registers needed by the CPUID intercept */
1849 		vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
1850 		vcpu->arch.regs[VCPU_REGS_RCX] = 0;
1851 
1852 		ret = svm_invoke_exit_handler(svm, SVM_EXIT_CPUID);
1853 		if (!ret) {
1854 			ret = -EINVAL;
1855 			break;
1856 		}
1857 
1858 		cpuid_reg = get_ghcb_msr_bits(svm,
1859 					      GHCB_MSR_CPUID_REG_MASK,
1860 					      GHCB_MSR_CPUID_REG_POS);
1861 		if (cpuid_reg == 0)
1862 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
1863 		else if (cpuid_reg == 1)
1864 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
1865 		else if (cpuid_reg == 2)
1866 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
1867 		else
1868 			cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
1869 
1870 		set_ghcb_msr_bits(svm, cpuid_value,
1871 				  GHCB_MSR_CPUID_VALUE_MASK,
1872 				  GHCB_MSR_CPUID_VALUE_POS);
1873 
1874 		set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
1875 				  GHCB_MSR_INFO_MASK,
1876 				  GHCB_MSR_INFO_POS);
1877 		break;
1878 	}
1879 	case GHCB_MSR_TERM_REQ: {
1880 		u64 reason_set, reason_code;
1881 
1882 		reason_set = get_ghcb_msr_bits(svm,
1883 					       GHCB_MSR_TERM_REASON_SET_MASK,
1884 					       GHCB_MSR_TERM_REASON_SET_POS);
1885 		reason_code = get_ghcb_msr_bits(svm,
1886 						GHCB_MSR_TERM_REASON_MASK,
1887 						GHCB_MSR_TERM_REASON_POS);
1888 		pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
1889 			reason_set, reason_code);
1890 		fallthrough;
1891 	}
1892 	default:
1893 		ret = -EINVAL;
1894 	}
1895 
1896 	trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
1897 					    control->ghcb_gpa, ret);
1898 
1899 	return ret;
1900 }
1901 
1902 int sev_handle_vmgexit(struct vcpu_svm *svm)
1903 {
1904 	struct vmcb_control_area *control = &svm->vmcb->control;
1905 	u64 ghcb_gpa, exit_code;
1906 	struct ghcb *ghcb;
1907 	int ret;
1908 
1909 	/* Validate the GHCB */
1910 	ghcb_gpa = control->ghcb_gpa;
1911 	if (ghcb_gpa & GHCB_MSR_INFO_MASK)
1912 		return sev_handle_vmgexit_msr_protocol(svm);
1913 
1914 	if (!ghcb_gpa) {
1915 		vcpu_unimpl(&svm->vcpu, "vmgexit: GHCB gpa is not set\n");
1916 		return -EINVAL;
1917 	}
1918 
1919 	if (kvm_vcpu_map(&svm->vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->ghcb_map)) {
1920 		/* Unable to map GHCB from guest */
1921 		vcpu_unimpl(&svm->vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
1922 			    ghcb_gpa);
1923 		return -EINVAL;
1924 	}
1925 
1926 	svm->ghcb = svm->ghcb_map.hva;
1927 	ghcb = svm->ghcb_map.hva;
1928 
1929 	trace_kvm_vmgexit_enter(svm->vcpu.vcpu_id, ghcb);
1930 
1931 	exit_code = ghcb_get_sw_exit_code(ghcb);
1932 
1933 	ret = sev_es_validate_vmgexit(svm);
1934 	if (ret)
1935 		return ret;
1936 
1937 	sev_es_sync_from_ghcb(svm);
1938 	ghcb_set_sw_exit_info_1(ghcb, 0);
1939 	ghcb_set_sw_exit_info_2(ghcb, 0);
1940 
1941 	ret = -EINVAL;
1942 	switch (exit_code) {
1943 	case SVM_VMGEXIT_MMIO_READ:
1944 		if (!setup_vmgexit_scratch(svm, true, control->exit_info_2))
1945 			break;
1946 
1947 		ret = kvm_sev_es_mmio_read(&svm->vcpu,
1948 					   control->exit_info_1,
1949 					   control->exit_info_2,
1950 					   svm->ghcb_sa);
1951 		break;
1952 	case SVM_VMGEXIT_MMIO_WRITE:
1953 		if (!setup_vmgexit_scratch(svm, false, control->exit_info_2))
1954 			break;
1955 
1956 		ret = kvm_sev_es_mmio_write(&svm->vcpu,
1957 					    control->exit_info_1,
1958 					    control->exit_info_2,
1959 					    svm->ghcb_sa);
1960 		break;
1961 	case SVM_VMGEXIT_NMI_COMPLETE:
1962 		ret = svm_invoke_exit_handler(svm, SVM_EXIT_IRET);
1963 		break;
1964 	case SVM_VMGEXIT_AP_HLT_LOOP:
1965 		ret = kvm_emulate_ap_reset_hold(&svm->vcpu);
1966 		break;
1967 	case SVM_VMGEXIT_AP_JUMP_TABLE: {
1968 		struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
1969 
1970 		switch (control->exit_info_1) {
1971 		case 0:
1972 			/* Set AP jump table address */
1973 			sev->ap_jump_table = control->exit_info_2;
1974 			break;
1975 		case 1:
1976 			/* Get AP jump table address */
1977 			ghcb_set_sw_exit_info_2(ghcb, sev->ap_jump_table);
1978 			break;
1979 		default:
1980 			pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
1981 			       control->exit_info_1);
1982 			ghcb_set_sw_exit_info_1(ghcb, 1);
1983 			ghcb_set_sw_exit_info_2(ghcb,
1984 						X86_TRAP_UD |
1985 						SVM_EVTINJ_TYPE_EXEPT |
1986 						SVM_EVTINJ_VALID);
1987 		}
1988 
1989 		ret = 1;
1990 		break;
1991 	}
1992 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
1993 		vcpu_unimpl(&svm->vcpu,
1994 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
1995 			    control->exit_info_1, control->exit_info_2);
1996 		break;
1997 	default:
1998 		ret = svm_invoke_exit_handler(svm, exit_code);
1999 	}
2000 
2001 	return ret;
2002 }
2003 
2004 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
2005 {
2006 	if (!setup_vmgexit_scratch(svm, in, svm->vmcb->control.exit_info_2))
2007 		return -EINVAL;
2008 
2009 	return kvm_sev_es_string_io(&svm->vcpu, size, port,
2010 				    svm->ghcb_sa, svm->ghcb_sa_len, in);
2011 }
2012 
2013 void sev_es_init_vmcb(struct vcpu_svm *svm)
2014 {
2015 	struct kvm_vcpu *vcpu = &svm->vcpu;
2016 
2017 	svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE;
2018 	svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
2019 
2020 	/*
2021 	 * An SEV-ES guest requires a VMSA area that is a separate from the
2022 	 * VMCB page. Do not include the encryption mask on the VMSA physical
2023 	 * address since hardware will access it using the guest key.
2024 	 */
2025 	svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);
2026 
2027 	/* Can't intercept CR register access, HV can't modify CR registers */
2028 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
2029 	svm_clr_intercept(svm, INTERCEPT_CR4_READ);
2030 	svm_clr_intercept(svm, INTERCEPT_CR8_READ);
2031 	svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
2032 	svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
2033 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
2034 
2035 	svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
2036 
2037 	/* Track EFER/CR register changes */
2038 	svm_set_intercept(svm, TRAP_EFER_WRITE);
2039 	svm_set_intercept(svm, TRAP_CR0_WRITE);
2040 	svm_set_intercept(svm, TRAP_CR4_WRITE);
2041 	svm_set_intercept(svm, TRAP_CR8_WRITE);
2042 
2043 	/* No support for enable_vmware_backdoor */
2044 	clr_exception_intercept(svm, GP_VECTOR);
2045 
2046 	/* Can't intercept XSETBV, HV can't modify XCR0 directly */
2047 	svm_clr_intercept(svm, INTERCEPT_XSETBV);
2048 
2049 	/* Clear intercepts on selected MSRs */
2050 	set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1);
2051 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1);
2052 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
2053 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
2054 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
2055 	set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
2056 }
2057 
2058 void sev_es_create_vcpu(struct vcpu_svm *svm)
2059 {
2060 	/*
2061 	 * Set the GHCB MSR value as per the GHCB specification when creating
2062 	 * a vCPU for an SEV-ES guest.
2063 	 */
2064 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
2065 					    GHCB_VERSION_MIN,
2066 					    sev_enc_bit));
2067 }
2068 
2069 void sev_es_prepare_guest_switch(struct vcpu_svm *svm, unsigned int cpu)
2070 {
2071 	struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2072 	struct vmcb_save_area *hostsa;
2073 
2074 	/*
2075 	 * As an SEV-ES guest, hardware will restore the host state on VMEXIT,
2076 	 * of which one step is to perform a VMLOAD. Since hardware does not
2077 	 * perform a VMSAVE on VMRUN, the host savearea must be updated.
2078 	 */
2079 	vmsave(__sme_page_pa(sd->save_area));
2080 
2081 	/* XCR0 is restored on VMEXIT, save the current host value */
2082 	hostsa = (struct vmcb_save_area *)(page_address(sd->save_area) + 0x400);
2083 	hostsa->xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
2084 
2085 	/* PKRU is restored on VMEXIT, save the curent host value */
2086 	hostsa->pkru = read_pkru();
2087 
2088 	/* MSR_IA32_XSS is restored on VMEXIT, save the currnet host value */
2089 	hostsa->xss = host_xss;
2090 }
2091 
2092 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
2093 {
2094 	struct vcpu_svm *svm = to_svm(vcpu);
2095 
2096 	/* First SIPI: Use the values as initially set by the VMM */
2097 	if (!svm->received_first_sipi) {
2098 		svm->received_first_sipi = true;
2099 		return;
2100 	}
2101 
2102 	/*
2103 	 * Subsequent SIPI: Return from an AP Reset Hold VMGEXIT, where
2104 	 * the guest will set the CS and RIP. Set SW_EXIT_INFO_2 to a
2105 	 * non-zero value.
2106 	 */
2107 	ghcb_set_sw_exit_info_2(svm->ghcb, 1);
2108 }
2109