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 #include <uapi/linux/sev-guest.h>
23
24 #include <asm/pkru.h>
25 #include <asm/trapnr.h>
26 #include <asm/fpu/xcr.h>
27 #include <asm/fpu/xstate.h>
28 #include <asm/debugreg.h>
29 #include <asm/sev.h>
30
31 #include "mmu.h"
32 #include "x86.h"
33 #include "svm.h"
34 #include "svm_ops.h"
35 #include "cpuid.h"
36 #include "trace.h"
37
38 #define GHCB_VERSION_MAX 2ULL
39 #define GHCB_VERSION_DEFAULT 2ULL
40 #define GHCB_VERSION_MIN 1ULL
41
42 #define GHCB_HV_FT_SUPPORTED (GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)
43
44 /* enable/disable SEV support */
45 static bool sev_enabled = true;
46 module_param_named(sev, sev_enabled, bool, 0444);
47
48 /* enable/disable SEV-ES support */
49 static bool sev_es_enabled = true;
50 module_param_named(sev_es, sev_es_enabled, bool, 0444);
51
52 /* enable/disable SEV-SNP support */
53 static bool sev_snp_enabled = true;
54 module_param_named(sev_snp, sev_snp_enabled, bool, 0444);
55
56 /* enable/disable SEV-ES DebugSwap support */
57 static bool sev_es_debug_swap_enabled = true;
58 module_param_named(debug_swap, sev_es_debug_swap_enabled, bool, 0444);
59 static u64 sev_supported_vmsa_features;
60
61 #define AP_RESET_HOLD_NONE 0
62 #define AP_RESET_HOLD_NAE_EVENT 1
63 #define AP_RESET_HOLD_MSR_PROTO 2
64
65 /* As defined by SEV-SNP Firmware ABI, under "Guest Policy". */
66 #define SNP_POLICY_MASK_API_MINOR GENMASK_ULL(7, 0)
67 #define SNP_POLICY_MASK_API_MAJOR GENMASK_ULL(15, 8)
68 #define SNP_POLICY_MASK_SMT BIT_ULL(16)
69 #define SNP_POLICY_MASK_RSVD_MBO BIT_ULL(17)
70 #define SNP_POLICY_MASK_DEBUG BIT_ULL(19)
71 #define SNP_POLICY_MASK_SINGLE_SOCKET BIT_ULL(20)
72
73 #define SNP_POLICY_MASK_VALID (SNP_POLICY_MASK_API_MINOR | \
74 SNP_POLICY_MASK_API_MAJOR | \
75 SNP_POLICY_MASK_SMT | \
76 SNP_POLICY_MASK_RSVD_MBO | \
77 SNP_POLICY_MASK_DEBUG | \
78 SNP_POLICY_MASK_SINGLE_SOCKET)
79
80 #define INITIAL_VMSA_GPA 0xFFFFFFFFF000
81
82 static u8 sev_enc_bit;
83 static DECLARE_RWSEM(sev_deactivate_lock);
84 static DEFINE_MUTEX(sev_bitmap_lock);
85 unsigned int max_sev_asid;
86 static unsigned int min_sev_asid;
87 static unsigned long sev_me_mask;
88 static unsigned int nr_asids;
89 static unsigned long *sev_asid_bitmap;
90 static unsigned long *sev_reclaim_asid_bitmap;
91
92 static int snp_decommission_context(struct kvm *kvm);
93
94 struct enc_region {
95 struct list_head list;
96 unsigned long npages;
97 struct page **pages;
98 unsigned long uaddr;
99 unsigned long size;
100 };
101
102 /* Called with the sev_bitmap_lock held, or on shutdown */
sev_flush_asids(unsigned int min_asid,unsigned int max_asid)103 static int sev_flush_asids(unsigned int min_asid, unsigned int max_asid)
104 {
105 int ret, error = 0;
106 unsigned int asid;
107
108 /* Check if there are any ASIDs to reclaim before performing a flush */
109 asid = find_next_bit(sev_reclaim_asid_bitmap, nr_asids, min_asid);
110 if (asid > max_asid)
111 return -EBUSY;
112
113 /*
114 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
115 * so it must be guarded.
116 */
117 down_write(&sev_deactivate_lock);
118
119 wbinvd_on_all_cpus();
120
121 if (sev_snp_enabled)
122 ret = sev_do_cmd(SEV_CMD_SNP_DF_FLUSH, NULL, &error);
123 else
124 ret = sev_guest_df_flush(&error);
125
126 up_write(&sev_deactivate_lock);
127
128 if (ret)
129 pr_err("SEV%s: DF_FLUSH failed, ret=%d, error=%#x\n",
130 sev_snp_enabled ? "-SNP" : "", ret, error);
131
132 return ret;
133 }
134
is_mirroring_enc_context(struct kvm * kvm)135 static inline bool is_mirroring_enc_context(struct kvm *kvm)
136 {
137 return !!to_kvm_sev_info(kvm)->enc_context_owner;
138 }
139
sev_vcpu_has_debug_swap(struct vcpu_svm * svm)140 static bool sev_vcpu_has_debug_swap(struct vcpu_svm *svm)
141 {
142 struct kvm_vcpu *vcpu = &svm->vcpu;
143 struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
144
145 return sev->vmsa_features & SVM_SEV_FEAT_DEBUG_SWAP;
146 }
147
148 /* Must be called with the sev_bitmap_lock held */
__sev_recycle_asids(unsigned int min_asid,unsigned int max_asid)149 static bool __sev_recycle_asids(unsigned int min_asid, unsigned int max_asid)
150 {
151 if (sev_flush_asids(min_asid, max_asid))
152 return false;
153
154 /* The flush process will flush all reclaimable SEV and SEV-ES ASIDs */
155 bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
156 nr_asids);
157 bitmap_zero(sev_reclaim_asid_bitmap, nr_asids);
158
159 return true;
160 }
161
sev_misc_cg_try_charge(struct kvm_sev_info * sev)162 static int sev_misc_cg_try_charge(struct kvm_sev_info *sev)
163 {
164 enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
165 return misc_cg_try_charge(type, sev->misc_cg, 1);
166 }
167
sev_misc_cg_uncharge(struct kvm_sev_info * sev)168 static void sev_misc_cg_uncharge(struct kvm_sev_info *sev)
169 {
170 enum misc_res_type type = sev->es_active ? MISC_CG_RES_SEV_ES : MISC_CG_RES_SEV;
171 misc_cg_uncharge(type, sev->misc_cg, 1);
172 }
173
sev_asid_new(struct kvm_sev_info * sev)174 static int sev_asid_new(struct kvm_sev_info *sev)
175 {
176 /*
177 * SEV-enabled guests must use asid from min_sev_asid to max_sev_asid.
178 * SEV-ES-enabled guest can use from 1 to min_sev_asid - 1.
179 * Note: min ASID can end up larger than the max if basic SEV support is
180 * effectively disabled by disallowing use of ASIDs for SEV guests.
181 */
182 unsigned int min_asid = sev->es_active ? 1 : min_sev_asid;
183 unsigned int max_asid = sev->es_active ? min_sev_asid - 1 : max_sev_asid;
184 unsigned int asid;
185 bool retry = true;
186 int ret;
187
188 if (min_asid > max_asid)
189 return -ENOTTY;
190
191 WARN_ON(sev->misc_cg);
192 sev->misc_cg = get_current_misc_cg();
193 ret = sev_misc_cg_try_charge(sev);
194 if (ret) {
195 put_misc_cg(sev->misc_cg);
196 sev->misc_cg = NULL;
197 return ret;
198 }
199
200 mutex_lock(&sev_bitmap_lock);
201
202 again:
203 asid = find_next_zero_bit(sev_asid_bitmap, max_asid + 1, min_asid);
204 if (asid > max_asid) {
205 if (retry && __sev_recycle_asids(min_asid, max_asid)) {
206 retry = false;
207 goto again;
208 }
209 mutex_unlock(&sev_bitmap_lock);
210 ret = -EBUSY;
211 goto e_uncharge;
212 }
213
214 __set_bit(asid, sev_asid_bitmap);
215
216 mutex_unlock(&sev_bitmap_lock);
217
218 sev->asid = asid;
219 return 0;
220 e_uncharge:
221 sev_misc_cg_uncharge(sev);
222 put_misc_cg(sev->misc_cg);
223 sev->misc_cg = NULL;
224 return ret;
225 }
226
sev_get_asid(struct kvm * kvm)227 static unsigned int sev_get_asid(struct kvm *kvm)
228 {
229 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
230
231 return sev->asid;
232 }
233
sev_asid_free(struct kvm_sev_info * sev)234 static void sev_asid_free(struct kvm_sev_info *sev)
235 {
236 struct svm_cpu_data *sd;
237 int cpu;
238
239 mutex_lock(&sev_bitmap_lock);
240
241 __set_bit(sev->asid, sev_reclaim_asid_bitmap);
242
243 for_each_possible_cpu(cpu) {
244 sd = per_cpu_ptr(&svm_data, cpu);
245 sd->sev_vmcbs[sev->asid] = NULL;
246 }
247
248 mutex_unlock(&sev_bitmap_lock);
249
250 sev_misc_cg_uncharge(sev);
251 put_misc_cg(sev->misc_cg);
252 sev->misc_cg = NULL;
253 }
254
sev_decommission(unsigned int handle)255 static void sev_decommission(unsigned int handle)
256 {
257 struct sev_data_decommission decommission;
258
259 if (!handle)
260 return;
261
262 decommission.handle = handle;
263 sev_guest_decommission(&decommission, NULL);
264 }
265
266 /*
267 * Transition a page to hypervisor-owned/shared state in the RMP table. This
268 * should not fail under normal conditions, but leak the page should that
269 * happen since it will no longer be usable by the host due to RMP protections.
270 */
kvm_rmp_make_shared(struct kvm * kvm,u64 pfn,enum pg_level level)271 static int kvm_rmp_make_shared(struct kvm *kvm, u64 pfn, enum pg_level level)
272 {
273 if (KVM_BUG_ON(rmp_make_shared(pfn, level), kvm)) {
274 snp_leak_pages(pfn, page_level_size(level) >> PAGE_SHIFT);
275 return -EIO;
276 }
277
278 return 0;
279 }
280
281 /*
282 * Certain page-states, such as Pre-Guest and Firmware pages (as documented
283 * in Chapter 5 of the SEV-SNP Firmware ABI under "Page States") cannot be
284 * directly transitioned back to normal/hypervisor-owned state via RMPUPDATE
285 * unless they are reclaimed first.
286 *
287 * Until they are reclaimed and subsequently transitioned via RMPUPDATE, they
288 * might not be usable by the host due to being set as immutable or still
289 * being associated with a guest ASID.
290 *
291 * Bug the VM and leak the page if reclaim fails, or if the RMP entry can't be
292 * converted back to shared, as the page is no longer usable due to RMP
293 * protections, and it's infeasible for the guest to continue on.
294 */
snp_page_reclaim(struct kvm * kvm,u64 pfn)295 static int snp_page_reclaim(struct kvm *kvm, u64 pfn)
296 {
297 struct sev_data_snp_page_reclaim data = {0};
298 int fw_err, rc;
299
300 data.paddr = __sme_set(pfn << PAGE_SHIFT);
301 rc = sev_do_cmd(SEV_CMD_SNP_PAGE_RECLAIM, &data, &fw_err);
302 if (KVM_BUG(rc, kvm, "Failed to reclaim PFN %llx, rc %d fw_err %d", pfn, rc, fw_err)) {
303 snp_leak_pages(pfn, 1);
304 return -EIO;
305 }
306
307 if (kvm_rmp_make_shared(kvm, pfn, PG_LEVEL_4K))
308 return -EIO;
309
310 return rc;
311 }
312
sev_unbind_asid(struct kvm * kvm,unsigned int handle)313 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
314 {
315 struct sev_data_deactivate deactivate;
316
317 if (!handle)
318 return;
319
320 deactivate.handle = handle;
321
322 /* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
323 down_read(&sev_deactivate_lock);
324 sev_guest_deactivate(&deactivate, NULL);
325 up_read(&sev_deactivate_lock);
326
327 sev_decommission(handle);
328 }
329
330 /*
331 * This sets up bounce buffers/firmware pages to handle SNP Guest Request
332 * messages (e.g. attestation requests). See "SNP Guest Request" in the GHCB
333 * 2.0 specification for more details.
334 *
335 * Technically, when an SNP Guest Request is issued, the guest will provide its
336 * own request/response pages, which could in theory be passed along directly
337 * to firmware rather than using bounce pages. However, these pages would need
338 * special care:
339 *
340 * - Both pages are from shared guest memory, so they need to be protected
341 * from migration/etc. occurring while firmware reads/writes to them. At a
342 * minimum, this requires elevating the ref counts and potentially needing
343 * an explicit pinning of the memory. This places additional restrictions
344 * on what type of memory backends userspace can use for shared guest
345 * memory since there is some reliance on using refcounted pages.
346 *
347 * - The response page needs to be switched to Firmware-owned[1] state
348 * before the firmware can write to it, which can lead to potential
349 * host RMP #PFs if the guest is misbehaved and hands the host a
350 * guest page that KVM might write to for other reasons (e.g. virtio
351 * buffers/etc.).
352 *
353 * Both of these issues can be avoided completely by using separately-allocated
354 * bounce pages for both the request/response pages and passing those to
355 * firmware instead. So that's what is being set up here.
356 *
357 * Guest requests rely on message sequence numbers to ensure requests are
358 * issued to firmware in the order the guest issues them, so concurrent guest
359 * requests generally shouldn't happen. But a misbehaved guest could issue
360 * concurrent guest requests in theory, so a mutex is used to serialize
361 * access to the bounce buffers.
362 *
363 * [1] See the "Page States" section of the SEV-SNP Firmware ABI for more
364 * details on Firmware-owned pages, along with "RMP and VMPL Access Checks"
365 * in the APM for details on the related RMP restrictions.
366 */
snp_guest_req_init(struct kvm * kvm)367 static int snp_guest_req_init(struct kvm *kvm)
368 {
369 struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
370 struct page *req_page;
371
372 req_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
373 if (!req_page)
374 return -ENOMEM;
375
376 sev->guest_resp_buf = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
377 if (!sev->guest_resp_buf) {
378 __free_page(req_page);
379 return -EIO;
380 }
381
382 sev->guest_req_buf = page_address(req_page);
383 mutex_init(&sev->guest_req_mutex);
384
385 return 0;
386 }
387
snp_guest_req_cleanup(struct kvm * kvm)388 static void snp_guest_req_cleanup(struct kvm *kvm)
389 {
390 struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
391
392 if (sev->guest_resp_buf)
393 snp_free_firmware_page(sev->guest_resp_buf);
394
395 if (sev->guest_req_buf)
396 __free_page(virt_to_page(sev->guest_req_buf));
397
398 sev->guest_req_buf = NULL;
399 sev->guest_resp_buf = NULL;
400 }
401
__sev_guest_init(struct kvm * kvm,struct kvm_sev_cmd * argp,struct kvm_sev_init * data,unsigned long vm_type)402 static int __sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp,
403 struct kvm_sev_init *data,
404 unsigned long vm_type)
405 {
406 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
407 struct sev_platform_init_args init_args = {0};
408 bool es_active = vm_type != KVM_X86_SEV_VM;
409 u64 valid_vmsa_features = es_active ? sev_supported_vmsa_features : 0;
410 int ret;
411
412 if (kvm->created_vcpus)
413 return -EINVAL;
414
415 if (data->flags)
416 return -EINVAL;
417
418 if (data->vmsa_features & ~valid_vmsa_features)
419 return -EINVAL;
420
421 if (data->ghcb_version > GHCB_VERSION_MAX || (!es_active && data->ghcb_version))
422 return -EINVAL;
423
424 if (unlikely(sev->active))
425 return -EINVAL;
426
427 sev->active = true;
428 sev->es_active = es_active;
429 sev->vmsa_features = data->vmsa_features;
430 sev->ghcb_version = data->ghcb_version;
431
432 /*
433 * Currently KVM supports the full range of mandatory features defined
434 * by version 2 of the GHCB protocol, so default to that for SEV-ES
435 * guests created via KVM_SEV_INIT2.
436 */
437 if (sev->es_active && !sev->ghcb_version)
438 sev->ghcb_version = GHCB_VERSION_DEFAULT;
439
440 if (vm_type == KVM_X86_SNP_VM)
441 sev->vmsa_features |= SVM_SEV_FEAT_SNP_ACTIVE;
442
443 ret = sev_asid_new(sev);
444 if (ret)
445 goto e_no_asid;
446
447 init_args.probe = false;
448 ret = sev_platform_init(&init_args);
449 if (ret)
450 goto e_free;
451
452 /* This needs to happen after SEV/SNP firmware initialization. */
453 if (vm_type == KVM_X86_SNP_VM) {
454 ret = snp_guest_req_init(kvm);
455 if (ret)
456 goto e_free;
457 }
458
459 INIT_LIST_HEAD(&sev->regions_list);
460 INIT_LIST_HEAD(&sev->mirror_vms);
461 sev->need_init = false;
462
463 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_SEV);
464
465 return 0;
466
467 e_free:
468 argp->error = init_args.error;
469 sev_asid_free(sev);
470 sev->asid = 0;
471 e_no_asid:
472 sev->vmsa_features = 0;
473 sev->es_active = false;
474 sev->active = false;
475 return ret;
476 }
477
sev_guest_init(struct kvm * kvm,struct kvm_sev_cmd * argp)478 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
479 {
480 struct kvm_sev_init data = {
481 .vmsa_features = 0,
482 .ghcb_version = 0,
483 };
484 unsigned long vm_type;
485
486 if (kvm->arch.vm_type != KVM_X86_DEFAULT_VM)
487 return -EINVAL;
488
489 vm_type = (argp->id == KVM_SEV_INIT ? KVM_X86_SEV_VM : KVM_X86_SEV_ES_VM);
490
491 /*
492 * KVM_SEV_ES_INIT has been deprecated by KVM_SEV_INIT2, so it will
493 * continue to only ever support the minimal GHCB protocol version.
494 */
495 if (vm_type == KVM_X86_SEV_ES_VM)
496 data.ghcb_version = GHCB_VERSION_MIN;
497
498 return __sev_guest_init(kvm, argp, &data, vm_type);
499 }
500
sev_guest_init2(struct kvm * kvm,struct kvm_sev_cmd * argp)501 static int sev_guest_init2(struct kvm *kvm, struct kvm_sev_cmd *argp)
502 {
503 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
504 struct kvm_sev_init data;
505
506 if (!sev->need_init)
507 return -EINVAL;
508
509 if (kvm->arch.vm_type != KVM_X86_SEV_VM &&
510 kvm->arch.vm_type != KVM_X86_SEV_ES_VM &&
511 kvm->arch.vm_type != KVM_X86_SNP_VM)
512 return -EINVAL;
513
514 if (copy_from_user(&data, u64_to_user_ptr(argp->data), sizeof(data)))
515 return -EFAULT;
516
517 return __sev_guest_init(kvm, argp, &data, kvm->arch.vm_type);
518 }
519
sev_bind_asid(struct kvm * kvm,unsigned int handle,int * error)520 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
521 {
522 unsigned int asid = sev_get_asid(kvm);
523 struct sev_data_activate activate;
524 int ret;
525
526 /* activate ASID on the given handle */
527 activate.handle = handle;
528 activate.asid = asid;
529 ret = sev_guest_activate(&activate, error);
530
531 return ret;
532 }
533
__sev_issue_cmd(int fd,int id,void * data,int * error)534 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
535 {
536 CLASS(fd, f)(fd);
537
538 if (fd_empty(f))
539 return -EBADF;
540
541 return sev_issue_cmd_external_user(fd_file(f), id, data, error);
542 }
543
sev_issue_cmd(struct kvm * kvm,int id,void * data,int * error)544 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
545 {
546 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
547
548 return __sev_issue_cmd(sev->fd, id, data, error);
549 }
550
sev_launch_start(struct kvm * kvm,struct kvm_sev_cmd * argp)551 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
552 {
553 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
554 struct sev_data_launch_start start;
555 struct kvm_sev_launch_start params;
556 void *dh_blob, *session_blob;
557 int *error = &argp->error;
558 int ret;
559
560 if (!sev_guest(kvm))
561 return -ENOTTY;
562
563 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
564 return -EFAULT;
565
566 memset(&start, 0, sizeof(start));
567
568 dh_blob = NULL;
569 if (params.dh_uaddr) {
570 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
571 if (IS_ERR(dh_blob))
572 return PTR_ERR(dh_blob);
573
574 start.dh_cert_address = __sme_set(__pa(dh_blob));
575 start.dh_cert_len = params.dh_len;
576 }
577
578 session_blob = NULL;
579 if (params.session_uaddr) {
580 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
581 if (IS_ERR(session_blob)) {
582 ret = PTR_ERR(session_blob);
583 goto e_free_dh;
584 }
585
586 start.session_address = __sme_set(__pa(session_blob));
587 start.session_len = params.session_len;
588 }
589
590 start.handle = params.handle;
591 start.policy = params.policy;
592
593 /* create memory encryption context */
594 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, &start, error);
595 if (ret)
596 goto e_free_session;
597
598 /* Bind ASID to this guest */
599 ret = sev_bind_asid(kvm, start.handle, error);
600 if (ret) {
601 sev_decommission(start.handle);
602 goto e_free_session;
603 }
604
605 /* return handle to userspace */
606 params.handle = start.handle;
607 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, sizeof(params))) {
608 sev_unbind_asid(kvm, start.handle);
609 ret = -EFAULT;
610 goto e_free_session;
611 }
612
613 sev->handle = start.handle;
614 sev->fd = argp->sev_fd;
615
616 e_free_session:
617 kfree(session_blob);
618 e_free_dh:
619 kfree(dh_blob);
620 return ret;
621 }
622
sev_pin_memory(struct kvm * kvm,unsigned long uaddr,unsigned long ulen,unsigned long * n,int write)623 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
624 unsigned long ulen, unsigned long *n,
625 int write)
626 {
627 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
628 unsigned long npages, size;
629 int npinned;
630 unsigned long locked, lock_limit;
631 struct page **pages;
632 unsigned long first, last;
633 int ret;
634
635 lockdep_assert_held(&kvm->lock);
636
637 if (ulen == 0 || uaddr + ulen < uaddr)
638 return ERR_PTR(-EINVAL);
639
640 /* Calculate number of pages. */
641 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
642 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
643 npages = (last - first + 1);
644
645 locked = sev->pages_locked + npages;
646 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
647 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
648 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
649 return ERR_PTR(-ENOMEM);
650 }
651
652 if (WARN_ON_ONCE(npages > INT_MAX))
653 return ERR_PTR(-EINVAL);
654
655 /* Avoid using vmalloc for smaller buffers. */
656 size = npages * sizeof(struct page *);
657 if (size > PAGE_SIZE)
658 pages = __vmalloc(size, GFP_KERNEL_ACCOUNT);
659 else
660 pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
661
662 if (!pages)
663 return ERR_PTR(-ENOMEM);
664
665 /* Pin the user virtual address. */
666 npinned = pin_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
667 if (npinned != npages) {
668 pr_err("SEV: Failure locking %lu pages.\n", npages);
669 ret = -ENOMEM;
670 goto err;
671 }
672
673 *n = npages;
674 sev->pages_locked = locked;
675
676 return pages;
677
678 err:
679 if (npinned > 0)
680 unpin_user_pages(pages, npinned);
681
682 kvfree(pages);
683 return ERR_PTR(ret);
684 }
685
sev_unpin_memory(struct kvm * kvm,struct page ** pages,unsigned long npages)686 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
687 unsigned long npages)
688 {
689 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
690
691 unpin_user_pages(pages, npages);
692 kvfree(pages);
693 sev->pages_locked -= npages;
694 }
695
sev_clflush_pages(struct page * pages[],unsigned long npages)696 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
697 {
698 uint8_t *page_virtual;
699 unsigned long i;
700
701 if (this_cpu_has(X86_FEATURE_SME_COHERENT) || npages == 0 ||
702 pages == NULL)
703 return;
704
705 for (i = 0; i < npages; i++) {
706 page_virtual = kmap_local_page(pages[i]);
707 clflush_cache_range(page_virtual, PAGE_SIZE);
708 kunmap_local(page_virtual);
709 cond_resched();
710 }
711 }
712
get_num_contig_pages(unsigned long idx,struct page ** inpages,unsigned long npages)713 static unsigned long get_num_contig_pages(unsigned long idx,
714 struct page **inpages, unsigned long npages)
715 {
716 unsigned long paddr, next_paddr;
717 unsigned long i = idx + 1, pages = 1;
718
719 /* find the number of contiguous pages starting from idx */
720 paddr = __sme_page_pa(inpages[idx]);
721 while (i < npages) {
722 next_paddr = __sme_page_pa(inpages[i++]);
723 if ((paddr + PAGE_SIZE) == next_paddr) {
724 pages++;
725 paddr = next_paddr;
726 continue;
727 }
728 break;
729 }
730
731 return pages;
732 }
733
sev_launch_update_data(struct kvm * kvm,struct kvm_sev_cmd * argp)734 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
735 {
736 unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
737 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
738 struct kvm_sev_launch_update_data params;
739 struct sev_data_launch_update_data data;
740 struct page **inpages;
741 int ret;
742
743 if (!sev_guest(kvm))
744 return -ENOTTY;
745
746 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
747 return -EFAULT;
748
749 vaddr = params.uaddr;
750 size = params.len;
751 vaddr_end = vaddr + size;
752
753 /* Lock the user memory. */
754 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
755 if (IS_ERR(inpages))
756 return PTR_ERR(inpages);
757
758 /*
759 * Flush (on non-coherent CPUs) before LAUNCH_UPDATE encrypts pages in
760 * place; the cache may contain the data that was written unencrypted.
761 */
762 sev_clflush_pages(inpages, npages);
763
764 data.reserved = 0;
765 data.handle = sev->handle;
766
767 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
768 int offset, len;
769
770 /*
771 * If the user buffer is not page-aligned, calculate the offset
772 * within the page.
773 */
774 offset = vaddr & (PAGE_SIZE - 1);
775
776 /* Calculate the number of pages that can be encrypted in one go. */
777 pages = get_num_contig_pages(i, inpages, npages);
778
779 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
780
781 data.len = len;
782 data.address = __sme_page_pa(inpages[i]) + offset;
783 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, &data, &argp->error);
784 if (ret)
785 goto e_unpin;
786
787 size -= len;
788 next_vaddr = vaddr + len;
789 }
790
791 e_unpin:
792 /* content of memory is updated, mark pages dirty */
793 for (i = 0; i < npages; i++) {
794 set_page_dirty_lock(inpages[i]);
795 mark_page_accessed(inpages[i]);
796 }
797 /* unlock the user pages */
798 sev_unpin_memory(kvm, inpages, npages);
799 return ret;
800 }
801
sev_es_sync_vmsa(struct vcpu_svm * svm)802 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
803 {
804 struct kvm_vcpu *vcpu = &svm->vcpu;
805 struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
806 struct sev_es_save_area *save = svm->sev_es.vmsa;
807 struct xregs_state *xsave;
808 const u8 *s;
809 u8 *d;
810 int i;
811
812 /* Check some debug related fields before encrypting the VMSA */
813 if (svm->vcpu.guest_debug || (svm->vmcb->save.dr7 & ~DR7_FIXED_1))
814 return -EINVAL;
815
816 /*
817 * SEV-ES will use a VMSA that is pointed to by the VMCB, not
818 * the traditional VMSA that is part of the VMCB. Copy the
819 * traditional VMSA as it has been built so far (in prep
820 * for LAUNCH_UPDATE_VMSA) to be the initial SEV-ES state.
821 */
822 memcpy(save, &svm->vmcb->save, sizeof(svm->vmcb->save));
823
824 /* Sync registgers */
825 save->rax = svm->vcpu.arch.regs[VCPU_REGS_RAX];
826 save->rbx = svm->vcpu.arch.regs[VCPU_REGS_RBX];
827 save->rcx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
828 save->rdx = svm->vcpu.arch.regs[VCPU_REGS_RDX];
829 save->rsp = svm->vcpu.arch.regs[VCPU_REGS_RSP];
830 save->rbp = svm->vcpu.arch.regs[VCPU_REGS_RBP];
831 save->rsi = svm->vcpu.arch.regs[VCPU_REGS_RSI];
832 save->rdi = svm->vcpu.arch.regs[VCPU_REGS_RDI];
833 #ifdef CONFIG_X86_64
834 save->r8 = svm->vcpu.arch.regs[VCPU_REGS_R8];
835 save->r9 = svm->vcpu.arch.regs[VCPU_REGS_R9];
836 save->r10 = svm->vcpu.arch.regs[VCPU_REGS_R10];
837 save->r11 = svm->vcpu.arch.regs[VCPU_REGS_R11];
838 save->r12 = svm->vcpu.arch.regs[VCPU_REGS_R12];
839 save->r13 = svm->vcpu.arch.regs[VCPU_REGS_R13];
840 save->r14 = svm->vcpu.arch.regs[VCPU_REGS_R14];
841 save->r15 = svm->vcpu.arch.regs[VCPU_REGS_R15];
842 #endif
843 save->rip = svm->vcpu.arch.regs[VCPU_REGS_RIP];
844
845 /* Sync some non-GPR registers before encrypting */
846 save->xcr0 = svm->vcpu.arch.xcr0;
847 save->pkru = svm->vcpu.arch.pkru;
848 save->xss = svm->vcpu.arch.ia32_xss;
849 save->dr6 = svm->vcpu.arch.dr6;
850
851 save->sev_features = sev->vmsa_features;
852
853 /*
854 * Skip FPU and AVX setup with KVM_SEV_ES_INIT to avoid
855 * breaking older measurements.
856 */
857 if (vcpu->kvm->arch.vm_type != KVM_X86_DEFAULT_VM) {
858 xsave = &vcpu->arch.guest_fpu.fpstate->regs.xsave;
859 save->x87_dp = xsave->i387.rdp;
860 save->mxcsr = xsave->i387.mxcsr;
861 save->x87_ftw = xsave->i387.twd;
862 save->x87_fsw = xsave->i387.swd;
863 save->x87_fcw = xsave->i387.cwd;
864 save->x87_fop = xsave->i387.fop;
865 save->x87_ds = 0;
866 save->x87_cs = 0;
867 save->x87_rip = xsave->i387.rip;
868
869 for (i = 0; i < 8; i++) {
870 /*
871 * The format of the x87 save area is undocumented and
872 * definitely not what you would expect. It consists of
873 * an 8*8 bytes area with bytes 0-7, and an 8*2 bytes
874 * area with bytes 8-9 of each register.
875 */
876 d = save->fpreg_x87 + i * 8;
877 s = ((u8 *)xsave->i387.st_space) + i * 16;
878 memcpy(d, s, 8);
879 save->fpreg_x87[64 + i * 2] = s[8];
880 save->fpreg_x87[64 + i * 2 + 1] = s[9];
881 }
882 memcpy(save->fpreg_xmm, xsave->i387.xmm_space, 256);
883
884 s = get_xsave_addr(xsave, XFEATURE_YMM);
885 if (s)
886 memcpy(save->fpreg_ymm, s, 256);
887 else
888 memset(save->fpreg_ymm, 0, 256);
889 }
890
891 pr_debug("Virtual Machine Save Area (VMSA):\n");
892 print_hex_dump_debug("", DUMP_PREFIX_NONE, 16, 1, save, sizeof(*save), false);
893
894 return 0;
895 }
896
__sev_launch_update_vmsa(struct kvm * kvm,struct kvm_vcpu * vcpu,int * error)897 static int __sev_launch_update_vmsa(struct kvm *kvm, struct kvm_vcpu *vcpu,
898 int *error)
899 {
900 struct sev_data_launch_update_vmsa vmsa;
901 struct vcpu_svm *svm = to_svm(vcpu);
902 int ret;
903
904 if (vcpu->guest_debug) {
905 pr_warn_once("KVM_SET_GUEST_DEBUG for SEV-ES guest is not supported");
906 return -EINVAL;
907 }
908
909 /* Perform some pre-encryption checks against the VMSA */
910 ret = sev_es_sync_vmsa(svm);
911 if (ret)
912 return ret;
913
914 /*
915 * The LAUNCH_UPDATE_VMSA command will perform in-place encryption of
916 * the VMSA memory content (i.e it will write the same memory region
917 * with the guest's key), so invalidate it first.
918 */
919 clflush_cache_range(svm->sev_es.vmsa, PAGE_SIZE);
920
921 vmsa.reserved = 0;
922 vmsa.handle = to_kvm_sev_info(kvm)->handle;
923 vmsa.address = __sme_pa(svm->sev_es.vmsa);
924 vmsa.len = PAGE_SIZE;
925 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_VMSA, &vmsa, error);
926 if (ret)
927 return ret;
928
929 /*
930 * SEV-ES guests maintain an encrypted version of their FPU
931 * state which is restored and saved on VMRUN and VMEXIT.
932 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't
933 * do xsave/xrstor on it.
934 */
935 fpstate_set_confidential(&vcpu->arch.guest_fpu);
936 vcpu->arch.guest_state_protected = true;
937
938 /*
939 * SEV-ES guest mandates LBR Virtualization to be _always_ ON. Enable it
940 * only after setting guest_state_protected because KVM_SET_MSRS allows
941 * dynamic toggling of LBRV (for performance reason) on write access to
942 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set.
943 */
944 svm_enable_lbrv(vcpu);
945 return 0;
946 }
947
sev_launch_update_vmsa(struct kvm * kvm,struct kvm_sev_cmd * argp)948 static int sev_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
949 {
950 struct kvm_vcpu *vcpu;
951 unsigned long i;
952 int ret;
953
954 if (!sev_es_guest(kvm))
955 return -ENOTTY;
956
957 kvm_for_each_vcpu(i, vcpu, kvm) {
958 ret = mutex_lock_killable(&vcpu->mutex);
959 if (ret)
960 return ret;
961
962 ret = __sev_launch_update_vmsa(kvm, vcpu, &argp->error);
963
964 mutex_unlock(&vcpu->mutex);
965 if (ret)
966 return ret;
967 }
968
969 return 0;
970 }
971
sev_launch_measure(struct kvm * kvm,struct kvm_sev_cmd * argp)972 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
973 {
974 void __user *measure = u64_to_user_ptr(argp->data);
975 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
976 struct sev_data_launch_measure data;
977 struct kvm_sev_launch_measure params;
978 void __user *p = NULL;
979 void *blob = NULL;
980 int ret;
981
982 if (!sev_guest(kvm))
983 return -ENOTTY;
984
985 if (copy_from_user(¶ms, measure, sizeof(params)))
986 return -EFAULT;
987
988 memset(&data, 0, sizeof(data));
989
990 /* User wants to query the blob length */
991 if (!params.len)
992 goto cmd;
993
994 p = u64_to_user_ptr(params.uaddr);
995 if (p) {
996 if (params.len > SEV_FW_BLOB_MAX_SIZE)
997 return -EINVAL;
998
999 blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
1000 if (!blob)
1001 return -ENOMEM;
1002
1003 data.address = __psp_pa(blob);
1004 data.len = params.len;
1005 }
1006
1007 cmd:
1008 data.handle = sev->handle;
1009 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, &data, &argp->error);
1010
1011 /*
1012 * If we query the session length, FW responded with expected data.
1013 */
1014 if (!params.len)
1015 goto done;
1016
1017 if (ret)
1018 goto e_free_blob;
1019
1020 if (blob) {
1021 if (copy_to_user(p, blob, params.len))
1022 ret = -EFAULT;
1023 }
1024
1025 done:
1026 params.len = data.len;
1027 if (copy_to_user(measure, ¶ms, sizeof(params)))
1028 ret = -EFAULT;
1029 e_free_blob:
1030 kfree(blob);
1031 return ret;
1032 }
1033
sev_launch_finish(struct kvm * kvm,struct kvm_sev_cmd * argp)1034 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1035 {
1036 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1037 struct sev_data_launch_finish data;
1038
1039 if (!sev_guest(kvm))
1040 return -ENOTTY;
1041
1042 data.handle = sev->handle;
1043 return sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, &data, &argp->error);
1044 }
1045
sev_guest_status(struct kvm * kvm,struct kvm_sev_cmd * argp)1046 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
1047 {
1048 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1049 struct kvm_sev_guest_status params;
1050 struct sev_data_guest_status data;
1051 int ret;
1052
1053 if (!sev_guest(kvm))
1054 return -ENOTTY;
1055
1056 memset(&data, 0, sizeof(data));
1057
1058 data.handle = sev->handle;
1059 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, &data, &argp->error);
1060 if (ret)
1061 return ret;
1062
1063 params.policy = data.policy;
1064 params.state = data.state;
1065 params.handle = data.handle;
1066
1067 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, sizeof(params)))
1068 ret = -EFAULT;
1069
1070 return ret;
1071 }
1072
__sev_issue_dbg_cmd(struct kvm * kvm,unsigned long src,unsigned long dst,int size,int * error,bool enc)1073 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
1074 unsigned long dst, int size,
1075 int *error, bool enc)
1076 {
1077 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1078 struct sev_data_dbg data;
1079
1080 data.reserved = 0;
1081 data.handle = sev->handle;
1082 data.dst_addr = dst;
1083 data.src_addr = src;
1084 data.len = size;
1085
1086 return sev_issue_cmd(kvm,
1087 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
1088 &data, error);
1089 }
1090
__sev_dbg_decrypt(struct kvm * kvm,unsigned long src_paddr,unsigned long dst_paddr,int sz,int * err)1091 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
1092 unsigned long dst_paddr, int sz, int *err)
1093 {
1094 int offset;
1095
1096 /*
1097 * Its safe to read more than we are asked, caller should ensure that
1098 * destination has enough space.
1099 */
1100 offset = src_paddr & 15;
1101 src_paddr = round_down(src_paddr, 16);
1102 sz = round_up(sz + offset, 16);
1103
1104 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
1105 }
1106
__sev_dbg_decrypt_user(struct kvm * kvm,unsigned long paddr,void __user * dst_uaddr,unsigned long dst_paddr,int size,int * err)1107 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
1108 void __user *dst_uaddr,
1109 unsigned long dst_paddr,
1110 int size, int *err)
1111 {
1112 struct page *tpage = NULL;
1113 int ret, offset;
1114
1115 /* if inputs are not 16-byte then use intermediate buffer */
1116 if (!IS_ALIGNED(dst_paddr, 16) ||
1117 !IS_ALIGNED(paddr, 16) ||
1118 !IS_ALIGNED(size, 16)) {
1119 tpage = (void *)alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1120 if (!tpage)
1121 return -ENOMEM;
1122
1123 dst_paddr = __sme_page_pa(tpage);
1124 }
1125
1126 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
1127 if (ret)
1128 goto e_free;
1129
1130 if (tpage) {
1131 offset = paddr & 15;
1132 if (copy_to_user(dst_uaddr, page_address(tpage) + offset, size))
1133 ret = -EFAULT;
1134 }
1135
1136 e_free:
1137 if (tpage)
1138 __free_page(tpage);
1139
1140 return ret;
1141 }
1142
__sev_dbg_encrypt_user(struct kvm * kvm,unsigned long paddr,void __user * vaddr,unsigned long dst_paddr,void __user * dst_vaddr,int size,int * error)1143 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
1144 void __user *vaddr,
1145 unsigned long dst_paddr,
1146 void __user *dst_vaddr,
1147 int size, int *error)
1148 {
1149 struct page *src_tpage = NULL;
1150 struct page *dst_tpage = NULL;
1151 int ret, len = size;
1152
1153 /* If source buffer is not aligned then use an intermediate buffer */
1154 if (!IS_ALIGNED((unsigned long)vaddr, 16)) {
1155 src_tpage = alloc_page(GFP_KERNEL_ACCOUNT);
1156 if (!src_tpage)
1157 return -ENOMEM;
1158
1159 if (copy_from_user(page_address(src_tpage), vaddr, size)) {
1160 __free_page(src_tpage);
1161 return -EFAULT;
1162 }
1163
1164 paddr = __sme_page_pa(src_tpage);
1165 }
1166
1167 /*
1168 * If destination buffer or length is not aligned then do read-modify-write:
1169 * - decrypt destination in an intermediate buffer
1170 * - copy the source buffer in an intermediate buffer
1171 * - use the intermediate buffer as source buffer
1172 */
1173 if (!IS_ALIGNED((unsigned long)dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
1174 int dst_offset;
1175
1176 dst_tpage = alloc_page(GFP_KERNEL_ACCOUNT);
1177 if (!dst_tpage) {
1178 ret = -ENOMEM;
1179 goto e_free;
1180 }
1181
1182 ret = __sev_dbg_decrypt(kvm, dst_paddr,
1183 __sme_page_pa(dst_tpage), size, error);
1184 if (ret)
1185 goto e_free;
1186
1187 /*
1188 * If source is kernel buffer then use memcpy() otherwise
1189 * copy_from_user().
1190 */
1191 dst_offset = dst_paddr & 15;
1192
1193 if (src_tpage)
1194 memcpy(page_address(dst_tpage) + dst_offset,
1195 page_address(src_tpage), size);
1196 else {
1197 if (copy_from_user(page_address(dst_tpage) + dst_offset,
1198 vaddr, size)) {
1199 ret = -EFAULT;
1200 goto e_free;
1201 }
1202 }
1203
1204 paddr = __sme_page_pa(dst_tpage);
1205 dst_paddr = round_down(dst_paddr, 16);
1206 len = round_up(size, 16);
1207 }
1208
1209 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
1210
1211 e_free:
1212 if (src_tpage)
1213 __free_page(src_tpage);
1214 if (dst_tpage)
1215 __free_page(dst_tpage);
1216 return ret;
1217 }
1218
sev_dbg_crypt(struct kvm * kvm,struct kvm_sev_cmd * argp,bool dec)1219 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
1220 {
1221 unsigned long vaddr, vaddr_end, next_vaddr;
1222 unsigned long dst_vaddr;
1223 struct page **src_p, **dst_p;
1224 struct kvm_sev_dbg debug;
1225 unsigned long n;
1226 unsigned int size;
1227 int ret;
1228
1229 if (!sev_guest(kvm))
1230 return -ENOTTY;
1231
1232 if (copy_from_user(&debug, u64_to_user_ptr(argp->data), sizeof(debug)))
1233 return -EFAULT;
1234
1235 if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
1236 return -EINVAL;
1237 if (!debug.dst_uaddr)
1238 return -EINVAL;
1239
1240 vaddr = debug.src_uaddr;
1241 size = debug.len;
1242 vaddr_end = vaddr + size;
1243 dst_vaddr = debug.dst_uaddr;
1244
1245 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
1246 int len, s_off, d_off;
1247
1248 /* lock userspace source and destination page */
1249 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
1250 if (IS_ERR(src_p))
1251 return PTR_ERR(src_p);
1252
1253 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
1254 if (IS_ERR(dst_p)) {
1255 sev_unpin_memory(kvm, src_p, n);
1256 return PTR_ERR(dst_p);
1257 }
1258
1259 /*
1260 * Flush (on non-coherent CPUs) before DBG_{DE,EN}CRYPT read or modify
1261 * the pages; flush the destination too so that future accesses do not
1262 * see stale data.
1263 */
1264 sev_clflush_pages(src_p, 1);
1265 sev_clflush_pages(dst_p, 1);
1266
1267 /*
1268 * Since user buffer may not be page aligned, calculate the
1269 * offset within the page.
1270 */
1271 s_off = vaddr & ~PAGE_MASK;
1272 d_off = dst_vaddr & ~PAGE_MASK;
1273 len = min_t(size_t, (PAGE_SIZE - s_off), size);
1274
1275 if (dec)
1276 ret = __sev_dbg_decrypt_user(kvm,
1277 __sme_page_pa(src_p[0]) + s_off,
1278 (void __user *)dst_vaddr,
1279 __sme_page_pa(dst_p[0]) + d_off,
1280 len, &argp->error);
1281 else
1282 ret = __sev_dbg_encrypt_user(kvm,
1283 __sme_page_pa(src_p[0]) + s_off,
1284 (void __user *)vaddr,
1285 __sme_page_pa(dst_p[0]) + d_off,
1286 (void __user *)dst_vaddr,
1287 len, &argp->error);
1288
1289 sev_unpin_memory(kvm, src_p, n);
1290 sev_unpin_memory(kvm, dst_p, n);
1291
1292 if (ret)
1293 goto err;
1294
1295 next_vaddr = vaddr + len;
1296 dst_vaddr = dst_vaddr + len;
1297 size -= len;
1298 }
1299 err:
1300 return ret;
1301 }
1302
sev_launch_secret(struct kvm * kvm,struct kvm_sev_cmd * argp)1303 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
1304 {
1305 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1306 struct sev_data_launch_secret data;
1307 struct kvm_sev_launch_secret params;
1308 struct page **pages;
1309 void *blob, *hdr;
1310 unsigned long n, i;
1311 int ret, offset;
1312
1313 if (!sev_guest(kvm))
1314 return -ENOTTY;
1315
1316 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
1317 return -EFAULT;
1318
1319 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
1320 if (IS_ERR(pages))
1321 return PTR_ERR(pages);
1322
1323 /*
1324 * Flush (on non-coherent CPUs) before LAUNCH_SECRET encrypts pages in
1325 * place; the cache may contain the data that was written unencrypted.
1326 */
1327 sev_clflush_pages(pages, n);
1328
1329 /*
1330 * The secret must be copied into contiguous memory region, lets verify
1331 * that userspace memory pages are contiguous before we issue command.
1332 */
1333 if (get_num_contig_pages(0, pages, n) != n) {
1334 ret = -EINVAL;
1335 goto e_unpin_memory;
1336 }
1337
1338 memset(&data, 0, sizeof(data));
1339
1340 offset = params.guest_uaddr & (PAGE_SIZE - 1);
1341 data.guest_address = __sme_page_pa(pages[0]) + offset;
1342 data.guest_len = params.guest_len;
1343
1344 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1345 if (IS_ERR(blob)) {
1346 ret = PTR_ERR(blob);
1347 goto e_unpin_memory;
1348 }
1349
1350 data.trans_address = __psp_pa(blob);
1351 data.trans_len = params.trans_len;
1352
1353 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1354 if (IS_ERR(hdr)) {
1355 ret = PTR_ERR(hdr);
1356 goto e_free_blob;
1357 }
1358 data.hdr_address = __psp_pa(hdr);
1359 data.hdr_len = params.hdr_len;
1360
1361 data.handle = sev->handle;
1362 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, &data, &argp->error);
1363
1364 kfree(hdr);
1365
1366 e_free_blob:
1367 kfree(blob);
1368 e_unpin_memory:
1369 /* content of memory is updated, mark pages dirty */
1370 for (i = 0; i < n; i++) {
1371 set_page_dirty_lock(pages[i]);
1372 mark_page_accessed(pages[i]);
1373 }
1374 sev_unpin_memory(kvm, pages, n);
1375 return ret;
1376 }
1377
sev_get_attestation_report(struct kvm * kvm,struct kvm_sev_cmd * argp)1378 static int sev_get_attestation_report(struct kvm *kvm, struct kvm_sev_cmd *argp)
1379 {
1380 void __user *report = u64_to_user_ptr(argp->data);
1381 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1382 struct sev_data_attestation_report data;
1383 struct kvm_sev_attestation_report params;
1384 void __user *p;
1385 void *blob = NULL;
1386 int ret;
1387
1388 if (!sev_guest(kvm))
1389 return -ENOTTY;
1390
1391 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
1392 return -EFAULT;
1393
1394 memset(&data, 0, sizeof(data));
1395
1396 /* User wants to query the blob length */
1397 if (!params.len)
1398 goto cmd;
1399
1400 p = u64_to_user_ptr(params.uaddr);
1401 if (p) {
1402 if (params.len > SEV_FW_BLOB_MAX_SIZE)
1403 return -EINVAL;
1404
1405 blob = kzalloc(params.len, GFP_KERNEL_ACCOUNT);
1406 if (!blob)
1407 return -ENOMEM;
1408
1409 data.address = __psp_pa(blob);
1410 data.len = params.len;
1411 memcpy(data.mnonce, params.mnonce, sizeof(params.mnonce));
1412 }
1413 cmd:
1414 data.handle = sev->handle;
1415 ret = sev_issue_cmd(kvm, SEV_CMD_ATTESTATION_REPORT, &data, &argp->error);
1416 /*
1417 * If we query the session length, FW responded with expected data.
1418 */
1419 if (!params.len)
1420 goto done;
1421
1422 if (ret)
1423 goto e_free_blob;
1424
1425 if (blob) {
1426 if (copy_to_user(p, blob, params.len))
1427 ret = -EFAULT;
1428 }
1429
1430 done:
1431 params.len = data.len;
1432 if (copy_to_user(report, ¶ms, sizeof(params)))
1433 ret = -EFAULT;
1434 e_free_blob:
1435 kfree(blob);
1436 return ret;
1437 }
1438
1439 /* Userspace wants to query session length. */
1440 static int
__sev_send_start_query_session_length(struct kvm * kvm,struct kvm_sev_cmd * argp,struct kvm_sev_send_start * params)1441 __sev_send_start_query_session_length(struct kvm *kvm, struct kvm_sev_cmd *argp,
1442 struct kvm_sev_send_start *params)
1443 {
1444 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1445 struct sev_data_send_start data;
1446 int ret;
1447
1448 memset(&data, 0, sizeof(data));
1449 data.handle = sev->handle;
1450 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1451
1452 params->session_len = data.session_len;
1453 if (copy_to_user(u64_to_user_ptr(argp->data), params,
1454 sizeof(struct kvm_sev_send_start)))
1455 ret = -EFAULT;
1456
1457 return ret;
1458 }
1459
sev_send_start(struct kvm * kvm,struct kvm_sev_cmd * argp)1460 static int sev_send_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1461 {
1462 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1463 struct sev_data_send_start data;
1464 struct kvm_sev_send_start params;
1465 void *amd_certs, *session_data;
1466 void *pdh_cert, *plat_certs;
1467 int ret;
1468
1469 if (!sev_guest(kvm))
1470 return -ENOTTY;
1471
1472 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data),
1473 sizeof(struct kvm_sev_send_start)))
1474 return -EFAULT;
1475
1476 /* if session_len is zero, userspace wants to query the session length */
1477 if (!params.session_len)
1478 return __sev_send_start_query_session_length(kvm, argp,
1479 ¶ms);
1480
1481 /* some sanity checks */
1482 if (!params.pdh_cert_uaddr || !params.pdh_cert_len ||
1483 !params.session_uaddr || params.session_len > SEV_FW_BLOB_MAX_SIZE)
1484 return -EINVAL;
1485
1486 /* allocate the memory to hold the session data blob */
1487 session_data = kzalloc(params.session_len, GFP_KERNEL_ACCOUNT);
1488 if (!session_data)
1489 return -ENOMEM;
1490
1491 /* copy the certificate blobs from userspace */
1492 pdh_cert = psp_copy_user_blob(params.pdh_cert_uaddr,
1493 params.pdh_cert_len);
1494 if (IS_ERR(pdh_cert)) {
1495 ret = PTR_ERR(pdh_cert);
1496 goto e_free_session;
1497 }
1498
1499 plat_certs = psp_copy_user_blob(params.plat_certs_uaddr,
1500 params.plat_certs_len);
1501 if (IS_ERR(plat_certs)) {
1502 ret = PTR_ERR(plat_certs);
1503 goto e_free_pdh;
1504 }
1505
1506 amd_certs = psp_copy_user_blob(params.amd_certs_uaddr,
1507 params.amd_certs_len);
1508 if (IS_ERR(amd_certs)) {
1509 ret = PTR_ERR(amd_certs);
1510 goto e_free_plat_cert;
1511 }
1512
1513 /* populate the FW SEND_START field with system physical address */
1514 memset(&data, 0, sizeof(data));
1515 data.pdh_cert_address = __psp_pa(pdh_cert);
1516 data.pdh_cert_len = params.pdh_cert_len;
1517 data.plat_certs_address = __psp_pa(plat_certs);
1518 data.plat_certs_len = params.plat_certs_len;
1519 data.amd_certs_address = __psp_pa(amd_certs);
1520 data.amd_certs_len = params.amd_certs_len;
1521 data.session_address = __psp_pa(session_data);
1522 data.session_len = params.session_len;
1523 data.handle = sev->handle;
1524
1525 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_START, &data, &argp->error);
1526
1527 if (!ret && copy_to_user(u64_to_user_ptr(params.session_uaddr),
1528 session_data, params.session_len)) {
1529 ret = -EFAULT;
1530 goto e_free_amd_cert;
1531 }
1532
1533 params.policy = data.policy;
1534 params.session_len = data.session_len;
1535 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms,
1536 sizeof(struct kvm_sev_send_start)))
1537 ret = -EFAULT;
1538
1539 e_free_amd_cert:
1540 kfree(amd_certs);
1541 e_free_plat_cert:
1542 kfree(plat_certs);
1543 e_free_pdh:
1544 kfree(pdh_cert);
1545 e_free_session:
1546 kfree(session_data);
1547 return ret;
1548 }
1549
1550 /* Userspace wants to query either header or trans length. */
1551 static int
__sev_send_update_data_query_lengths(struct kvm * kvm,struct kvm_sev_cmd * argp,struct kvm_sev_send_update_data * params)1552 __sev_send_update_data_query_lengths(struct kvm *kvm, struct kvm_sev_cmd *argp,
1553 struct kvm_sev_send_update_data *params)
1554 {
1555 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1556 struct sev_data_send_update_data data;
1557 int ret;
1558
1559 memset(&data, 0, sizeof(data));
1560 data.handle = sev->handle;
1561 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1562
1563 params->hdr_len = data.hdr_len;
1564 params->trans_len = data.trans_len;
1565
1566 if (copy_to_user(u64_to_user_ptr(argp->data), params,
1567 sizeof(struct kvm_sev_send_update_data)))
1568 ret = -EFAULT;
1569
1570 return ret;
1571 }
1572
sev_send_update_data(struct kvm * kvm,struct kvm_sev_cmd * argp)1573 static int sev_send_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1574 {
1575 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1576 struct sev_data_send_update_data data;
1577 struct kvm_sev_send_update_data params;
1578 void *hdr, *trans_data;
1579 struct page **guest_page;
1580 unsigned long n;
1581 int ret, offset;
1582
1583 if (!sev_guest(kvm))
1584 return -ENOTTY;
1585
1586 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data),
1587 sizeof(struct kvm_sev_send_update_data)))
1588 return -EFAULT;
1589
1590 /* userspace wants to query either header or trans length */
1591 if (!params.trans_len || !params.hdr_len)
1592 return __sev_send_update_data_query_lengths(kvm, argp, ¶ms);
1593
1594 if (!params.trans_uaddr || !params.guest_uaddr ||
1595 !params.guest_len || !params.hdr_uaddr)
1596 return -EINVAL;
1597
1598 /* Check if we are crossing the page boundary */
1599 offset = params.guest_uaddr & (PAGE_SIZE - 1);
1600 if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1601 return -EINVAL;
1602
1603 /* Pin guest memory */
1604 guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1605 PAGE_SIZE, &n, 0);
1606 if (IS_ERR(guest_page))
1607 return PTR_ERR(guest_page);
1608
1609 /* allocate memory for header and transport buffer */
1610 ret = -ENOMEM;
1611 hdr = kzalloc(params.hdr_len, GFP_KERNEL_ACCOUNT);
1612 if (!hdr)
1613 goto e_unpin;
1614
1615 trans_data = kzalloc(params.trans_len, GFP_KERNEL_ACCOUNT);
1616 if (!trans_data)
1617 goto e_free_hdr;
1618
1619 memset(&data, 0, sizeof(data));
1620 data.hdr_address = __psp_pa(hdr);
1621 data.hdr_len = params.hdr_len;
1622 data.trans_address = __psp_pa(trans_data);
1623 data.trans_len = params.trans_len;
1624
1625 /* The SEND_UPDATE_DATA command requires C-bit to be always set. */
1626 data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1627 data.guest_address |= sev_me_mask;
1628 data.guest_len = params.guest_len;
1629 data.handle = sev->handle;
1630
1631 ret = sev_issue_cmd(kvm, SEV_CMD_SEND_UPDATE_DATA, &data, &argp->error);
1632
1633 if (ret)
1634 goto e_free_trans_data;
1635
1636 /* copy transport buffer to user space */
1637 if (copy_to_user(u64_to_user_ptr(params.trans_uaddr),
1638 trans_data, params.trans_len)) {
1639 ret = -EFAULT;
1640 goto e_free_trans_data;
1641 }
1642
1643 /* Copy packet header to userspace. */
1644 if (copy_to_user(u64_to_user_ptr(params.hdr_uaddr), hdr,
1645 params.hdr_len))
1646 ret = -EFAULT;
1647
1648 e_free_trans_data:
1649 kfree(trans_data);
1650 e_free_hdr:
1651 kfree(hdr);
1652 e_unpin:
1653 sev_unpin_memory(kvm, guest_page, n);
1654
1655 return ret;
1656 }
1657
sev_send_finish(struct kvm * kvm,struct kvm_sev_cmd * argp)1658 static int sev_send_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1659 {
1660 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1661 struct sev_data_send_finish data;
1662
1663 if (!sev_guest(kvm))
1664 return -ENOTTY;
1665
1666 data.handle = sev->handle;
1667 return sev_issue_cmd(kvm, SEV_CMD_SEND_FINISH, &data, &argp->error);
1668 }
1669
sev_send_cancel(struct kvm * kvm,struct kvm_sev_cmd * argp)1670 static int sev_send_cancel(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_send_cancel data;
1674
1675 if (!sev_guest(kvm))
1676 return -ENOTTY;
1677
1678 data.handle = sev->handle;
1679 return sev_issue_cmd(kvm, SEV_CMD_SEND_CANCEL, &data, &argp->error);
1680 }
1681
sev_receive_start(struct kvm * kvm,struct kvm_sev_cmd * argp)1682 static int sev_receive_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
1683 {
1684 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1685 struct sev_data_receive_start start;
1686 struct kvm_sev_receive_start params;
1687 int *error = &argp->error;
1688 void *session_data;
1689 void *pdh_data;
1690 int ret;
1691
1692 if (!sev_guest(kvm))
1693 return -ENOTTY;
1694
1695 /* Get parameter from the userspace */
1696 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data),
1697 sizeof(struct kvm_sev_receive_start)))
1698 return -EFAULT;
1699
1700 /* some sanity checks */
1701 if (!params.pdh_uaddr || !params.pdh_len ||
1702 !params.session_uaddr || !params.session_len)
1703 return -EINVAL;
1704
1705 pdh_data = psp_copy_user_blob(params.pdh_uaddr, params.pdh_len);
1706 if (IS_ERR(pdh_data))
1707 return PTR_ERR(pdh_data);
1708
1709 session_data = psp_copy_user_blob(params.session_uaddr,
1710 params.session_len);
1711 if (IS_ERR(session_data)) {
1712 ret = PTR_ERR(session_data);
1713 goto e_free_pdh;
1714 }
1715
1716 memset(&start, 0, sizeof(start));
1717 start.handle = params.handle;
1718 start.policy = params.policy;
1719 start.pdh_cert_address = __psp_pa(pdh_data);
1720 start.pdh_cert_len = params.pdh_len;
1721 start.session_address = __psp_pa(session_data);
1722 start.session_len = params.session_len;
1723
1724 /* create memory encryption context */
1725 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_RECEIVE_START, &start,
1726 error);
1727 if (ret)
1728 goto e_free_session;
1729
1730 /* Bind ASID to this guest */
1731 ret = sev_bind_asid(kvm, start.handle, error);
1732 if (ret) {
1733 sev_decommission(start.handle);
1734 goto e_free_session;
1735 }
1736
1737 params.handle = start.handle;
1738 if (copy_to_user(u64_to_user_ptr(argp->data),
1739 ¶ms, sizeof(struct kvm_sev_receive_start))) {
1740 ret = -EFAULT;
1741 sev_unbind_asid(kvm, start.handle);
1742 goto e_free_session;
1743 }
1744
1745 sev->handle = start.handle;
1746 sev->fd = argp->sev_fd;
1747
1748 e_free_session:
1749 kfree(session_data);
1750 e_free_pdh:
1751 kfree(pdh_data);
1752
1753 return ret;
1754 }
1755
sev_receive_update_data(struct kvm * kvm,struct kvm_sev_cmd * argp)1756 static int sev_receive_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
1757 {
1758 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1759 struct kvm_sev_receive_update_data params;
1760 struct sev_data_receive_update_data data;
1761 void *hdr = NULL, *trans = NULL;
1762 struct page **guest_page;
1763 unsigned long n;
1764 int ret, offset;
1765
1766 if (!sev_guest(kvm))
1767 return -EINVAL;
1768
1769 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data),
1770 sizeof(struct kvm_sev_receive_update_data)))
1771 return -EFAULT;
1772
1773 if (!params.hdr_uaddr || !params.hdr_len ||
1774 !params.guest_uaddr || !params.guest_len ||
1775 !params.trans_uaddr || !params.trans_len)
1776 return -EINVAL;
1777
1778 /* Check if we are crossing the page boundary */
1779 offset = params.guest_uaddr & (PAGE_SIZE - 1);
1780 if (params.guest_len > PAGE_SIZE || (params.guest_len + offset) > PAGE_SIZE)
1781 return -EINVAL;
1782
1783 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
1784 if (IS_ERR(hdr))
1785 return PTR_ERR(hdr);
1786
1787 trans = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
1788 if (IS_ERR(trans)) {
1789 ret = PTR_ERR(trans);
1790 goto e_free_hdr;
1791 }
1792
1793 memset(&data, 0, sizeof(data));
1794 data.hdr_address = __psp_pa(hdr);
1795 data.hdr_len = params.hdr_len;
1796 data.trans_address = __psp_pa(trans);
1797 data.trans_len = params.trans_len;
1798
1799 /* Pin guest memory */
1800 guest_page = sev_pin_memory(kvm, params.guest_uaddr & PAGE_MASK,
1801 PAGE_SIZE, &n, 1);
1802 if (IS_ERR(guest_page)) {
1803 ret = PTR_ERR(guest_page);
1804 goto e_free_trans;
1805 }
1806
1807 /*
1808 * Flush (on non-coherent CPUs) before RECEIVE_UPDATE_DATA, the PSP
1809 * encrypts the written data with the guest's key, and the cache may
1810 * contain dirty, unencrypted data.
1811 */
1812 sev_clflush_pages(guest_page, n);
1813
1814 /* The RECEIVE_UPDATE_DATA command requires C-bit to be always set. */
1815 data.guest_address = (page_to_pfn(guest_page[0]) << PAGE_SHIFT) + offset;
1816 data.guest_address |= sev_me_mask;
1817 data.guest_len = params.guest_len;
1818 data.handle = sev->handle;
1819
1820 ret = sev_issue_cmd(kvm, SEV_CMD_RECEIVE_UPDATE_DATA, &data,
1821 &argp->error);
1822
1823 sev_unpin_memory(kvm, guest_page, n);
1824
1825 e_free_trans:
1826 kfree(trans);
1827 e_free_hdr:
1828 kfree(hdr);
1829
1830 return ret;
1831 }
1832
sev_receive_finish(struct kvm * kvm,struct kvm_sev_cmd * argp)1833 static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
1834 {
1835 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1836 struct sev_data_receive_finish data;
1837
1838 if (!sev_guest(kvm))
1839 return -ENOTTY;
1840
1841 data.handle = sev->handle;
1842 return sev_issue_cmd(kvm, SEV_CMD_RECEIVE_FINISH, &data, &argp->error);
1843 }
1844
is_cmd_allowed_from_mirror(u32 cmd_id)1845 static bool is_cmd_allowed_from_mirror(u32 cmd_id)
1846 {
1847 /*
1848 * Allow mirrors VM to call KVM_SEV_LAUNCH_UPDATE_VMSA to enable SEV-ES
1849 * active mirror VMs. Also allow the debugging and status commands.
1850 */
1851 if (cmd_id == KVM_SEV_LAUNCH_UPDATE_VMSA ||
1852 cmd_id == KVM_SEV_GUEST_STATUS || cmd_id == KVM_SEV_DBG_DECRYPT ||
1853 cmd_id == KVM_SEV_DBG_ENCRYPT)
1854 return true;
1855
1856 return false;
1857 }
1858
sev_lock_two_vms(struct kvm * dst_kvm,struct kvm * src_kvm)1859 static int sev_lock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1860 {
1861 struct kvm_sev_info *dst_sev = &to_kvm_svm(dst_kvm)->sev_info;
1862 struct kvm_sev_info *src_sev = &to_kvm_svm(src_kvm)->sev_info;
1863 int r = -EBUSY;
1864
1865 if (dst_kvm == src_kvm)
1866 return -EINVAL;
1867
1868 /*
1869 * Bail if these VMs are already involved in a migration to avoid
1870 * deadlock between two VMs trying to migrate to/from each other.
1871 */
1872 if (atomic_cmpxchg_acquire(&dst_sev->migration_in_progress, 0, 1))
1873 return -EBUSY;
1874
1875 if (atomic_cmpxchg_acquire(&src_sev->migration_in_progress, 0, 1))
1876 goto release_dst;
1877
1878 r = -EINTR;
1879 if (mutex_lock_killable(&dst_kvm->lock))
1880 goto release_src;
1881 if (mutex_lock_killable_nested(&src_kvm->lock, SINGLE_DEPTH_NESTING))
1882 goto unlock_dst;
1883 return 0;
1884
1885 unlock_dst:
1886 mutex_unlock(&dst_kvm->lock);
1887 release_src:
1888 atomic_set_release(&src_sev->migration_in_progress, 0);
1889 release_dst:
1890 atomic_set_release(&dst_sev->migration_in_progress, 0);
1891 return r;
1892 }
1893
sev_unlock_two_vms(struct kvm * dst_kvm,struct kvm * src_kvm)1894 static void sev_unlock_two_vms(struct kvm *dst_kvm, struct kvm *src_kvm)
1895 {
1896 struct kvm_sev_info *dst_sev = &to_kvm_svm(dst_kvm)->sev_info;
1897 struct kvm_sev_info *src_sev = &to_kvm_svm(src_kvm)->sev_info;
1898
1899 mutex_unlock(&dst_kvm->lock);
1900 mutex_unlock(&src_kvm->lock);
1901 atomic_set_release(&dst_sev->migration_in_progress, 0);
1902 atomic_set_release(&src_sev->migration_in_progress, 0);
1903 }
1904
1905 /* vCPU mutex subclasses. */
1906 enum sev_migration_role {
1907 SEV_MIGRATION_SOURCE = 0,
1908 SEV_MIGRATION_TARGET,
1909 SEV_NR_MIGRATION_ROLES,
1910 };
1911
sev_lock_vcpus_for_migration(struct kvm * kvm,enum sev_migration_role role)1912 static int sev_lock_vcpus_for_migration(struct kvm *kvm,
1913 enum sev_migration_role role)
1914 {
1915 struct kvm_vcpu *vcpu;
1916 unsigned long i, j;
1917
1918 kvm_for_each_vcpu(i, vcpu, kvm) {
1919 if (mutex_lock_killable_nested(&vcpu->mutex, role))
1920 goto out_unlock;
1921
1922 #ifdef CONFIG_PROVE_LOCKING
1923 if (!i)
1924 /*
1925 * Reset the role to one that avoids colliding with
1926 * the role used for the first vcpu mutex.
1927 */
1928 role = SEV_NR_MIGRATION_ROLES;
1929 else
1930 mutex_release(&vcpu->mutex.dep_map, _THIS_IP_);
1931 #endif
1932 }
1933
1934 return 0;
1935
1936 out_unlock:
1937
1938 kvm_for_each_vcpu(j, vcpu, kvm) {
1939 if (i == j)
1940 break;
1941
1942 #ifdef CONFIG_PROVE_LOCKING
1943 if (j)
1944 mutex_acquire(&vcpu->mutex.dep_map, role, 0, _THIS_IP_);
1945 #endif
1946
1947 mutex_unlock(&vcpu->mutex);
1948 }
1949 return -EINTR;
1950 }
1951
sev_unlock_vcpus_for_migration(struct kvm * kvm)1952 static void sev_unlock_vcpus_for_migration(struct kvm *kvm)
1953 {
1954 struct kvm_vcpu *vcpu;
1955 unsigned long i;
1956 bool first = true;
1957
1958 kvm_for_each_vcpu(i, vcpu, kvm) {
1959 if (first)
1960 first = false;
1961 else
1962 mutex_acquire(&vcpu->mutex.dep_map,
1963 SEV_NR_MIGRATION_ROLES, 0, _THIS_IP_);
1964
1965 mutex_unlock(&vcpu->mutex);
1966 }
1967 }
1968
sev_migrate_from(struct kvm * dst_kvm,struct kvm * src_kvm)1969 static void sev_migrate_from(struct kvm *dst_kvm, struct kvm *src_kvm)
1970 {
1971 struct kvm_sev_info *dst = &to_kvm_svm(dst_kvm)->sev_info;
1972 struct kvm_sev_info *src = &to_kvm_svm(src_kvm)->sev_info;
1973 struct kvm_vcpu *dst_vcpu, *src_vcpu;
1974 struct vcpu_svm *dst_svm, *src_svm;
1975 struct kvm_sev_info *mirror;
1976 unsigned long i;
1977
1978 dst->active = true;
1979 dst->asid = src->asid;
1980 dst->handle = src->handle;
1981 dst->pages_locked = src->pages_locked;
1982 dst->enc_context_owner = src->enc_context_owner;
1983 dst->es_active = src->es_active;
1984 dst->vmsa_features = src->vmsa_features;
1985
1986 src->asid = 0;
1987 src->active = false;
1988 src->handle = 0;
1989 src->pages_locked = 0;
1990 src->enc_context_owner = NULL;
1991 src->es_active = false;
1992
1993 list_cut_before(&dst->regions_list, &src->regions_list, &src->regions_list);
1994
1995 /*
1996 * If this VM has mirrors, "transfer" each mirror's refcount of the
1997 * source to the destination (this KVM). The caller holds a reference
1998 * to the source, so there's no danger of use-after-free.
1999 */
2000 list_cut_before(&dst->mirror_vms, &src->mirror_vms, &src->mirror_vms);
2001 list_for_each_entry(mirror, &dst->mirror_vms, mirror_entry) {
2002 kvm_get_kvm(dst_kvm);
2003 kvm_put_kvm(src_kvm);
2004 mirror->enc_context_owner = dst_kvm;
2005 }
2006
2007 /*
2008 * If this VM is a mirror, remove the old mirror from the owners list
2009 * and add the new mirror to the list.
2010 */
2011 if (is_mirroring_enc_context(dst_kvm)) {
2012 struct kvm_sev_info *owner_sev_info =
2013 &to_kvm_svm(dst->enc_context_owner)->sev_info;
2014
2015 list_del(&src->mirror_entry);
2016 list_add_tail(&dst->mirror_entry, &owner_sev_info->mirror_vms);
2017 }
2018
2019 kvm_for_each_vcpu(i, dst_vcpu, dst_kvm) {
2020 dst_svm = to_svm(dst_vcpu);
2021
2022 sev_init_vmcb(dst_svm);
2023
2024 if (!dst->es_active)
2025 continue;
2026
2027 /*
2028 * Note, the source is not required to have the same number of
2029 * vCPUs as the destination when migrating a vanilla SEV VM.
2030 */
2031 src_vcpu = kvm_get_vcpu(src_kvm, i);
2032 src_svm = to_svm(src_vcpu);
2033
2034 /*
2035 * Transfer VMSA and GHCB state to the destination. Nullify and
2036 * clear source fields as appropriate, the state now belongs to
2037 * the destination.
2038 */
2039 memcpy(&dst_svm->sev_es, &src_svm->sev_es, sizeof(src_svm->sev_es));
2040 dst_svm->vmcb->control.ghcb_gpa = src_svm->vmcb->control.ghcb_gpa;
2041 dst_svm->vmcb->control.vmsa_pa = src_svm->vmcb->control.vmsa_pa;
2042 dst_vcpu->arch.guest_state_protected = true;
2043
2044 memset(&src_svm->sev_es, 0, sizeof(src_svm->sev_es));
2045 src_svm->vmcb->control.ghcb_gpa = INVALID_PAGE;
2046 src_svm->vmcb->control.vmsa_pa = INVALID_PAGE;
2047 src_vcpu->arch.guest_state_protected = false;
2048 }
2049 }
2050
sev_check_source_vcpus(struct kvm * dst,struct kvm * src)2051 static int sev_check_source_vcpus(struct kvm *dst, struct kvm *src)
2052 {
2053 struct kvm_vcpu *src_vcpu;
2054 unsigned long i;
2055
2056 if (!sev_es_guest(src))
2057 return 0;
2058
2059 if (atomic_read(&src->online_vcpus) != atomic_read(&dst->online_vcpus))
2060 return -EINVAL;
2061
2062 kvm_for_each_vcpu(i, src_vcpu, src) {
2063 if (!src_vcpu->arch.guest_state_protected)
2064 return -EINVAL;
2065 }
2066
2067 return 0;
2068 }
2069
sev_vm_move_enc_context_from(struct kvm * kvm,unsigned int source_fd)2070 int sev_vm_move_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2071 {
2072 struct kvm_sev_info *dst_sev = &to_kvm_svm(kvm)->sev_info;
2073 struct kvm_sev_info *src_sev, *cg_cleanup_sev;
2074 CLASS(fd, f)(source_fd);
2075 struct kvm *source_kvm;
2076 bool charged = false;
2077 int ret;
2078
2079 if (fd_empty(f))
2080 return -EBADF;
2081
2082 if (!file_is_kvm(fd_file(f)))
2083 return -EBADF;
2084
2085 source_kvm = fd_file(f)->private_data;
2086 ret = sev_lock_two_vms(kvm, source_kvm);
2087 if (ret)
2088 return ret;
2089
2090 if (kvm->arch.vm_type != source_kvm->arch.vm_type ||
2091 sev_guest(kvm) || !sev_guest(source_kvm)) {
2092 ret = -EINVAL;
2093 goto out_unlock;
2094 }
2095
2096 src_sev = &to_kvm_svm(source_kvm)->sev_info;
2097
2098 dst_sev->misc_cg = get_current_misc_cg();
2099 cg_cleanup_sev = dst_sev;
2100 if (dst_sev->misc_cg != src_sev->misc_cg) {
2101 ret = sev_misc_cg_try_charge(dst_sev);
2102 if (ret)
2103 goto out_dst_cgroup;
2104 charged = true;
2105 }
2106
2107 ret = sev_lock_vcpus_for_migration(kvm, SEV_MIGRATION_SOURCE);
2108 if (ret)
2109 goto out_dst_cgroup;
2110 ret = sev_lock_vcpus_for_migration(source_kvm, SEV_MIGRATION_TARGET);
2111 if (ret)
2112 goto out_dst_vcpu;
2113
2114 ret = sev_check_source_vcpus(kvm, source_kvm);
2115 if (ret)
2116 goto out_source_vcpu;
2117
2118 sev_migrate_from(kvm, source_kvm);
2119 kvm_vm_dead(source_kvm);
2120 cg_cleanup_sev = src_sev;
2121 ret = 0;
2122
2123 out_source_vcpu:
2124 sev_unlock_vcpus_for_migration(source_kvm);
2125 out_dst_vcpu:
2126 sev_unlock_vcpus_for_migration(kvm);
2127 out_dst_cgroup:
2128 /* Operates on the source on success, on the destination on failure. */
2129 if (charged)
2130 sev_misc_cg_uncharge(cg_cleanup_sev);
2131 put_misc_cg(cg_cleanup_sev->misc_cg);
2132 cg_cleanup_sev->misc_cg = NULL;
2133 out_unlock:
2134 sev_unlock_two_vms(kvm, source_kvm);
2135 return ret;
2136 }
2137
sev_dev_get_attr(u32 group,u64 attr,u64 * val)2138 int sev_dev_get_attr(u32 group, u64 attr, u64 *val)
2139 {
2140 if (group != KVM_X86_GRP_SEV)
2141 return -ENXIO;
2142
2143 switch (attr) {
2144 case KVM_X86_SEV_VMSA_FEATURES:
2145 *val = sev_supported_vmsa_features;
2146 return 0;
2147
2148 default:
2149 return -ENXIO;
2150 }
2151 }
2152
2153 /*
2154 * The guest context contains all the information, keys and metadata
2155 * associated with the guest that the firmware tracks to implement SEV
2156 * and SNP features. The firmware stores the guest context in hypervisor
2157 * provide page via the SNP_GCTX_CREATE command.
2158 */
snp_context_create(struct kvm * kvm,struct kvm_sev_cmd * argp)2159 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
2160 {
2161 struct sev_data_snp_addr data = {};
2162 void *context;
2163 int rc;
2164
2165 /* Allocate memory for context page */
2166 context = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
2167 if (!context)
2168 return NULL;
2169
2170 data.address = __psp_pa(context);
2171 rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
2172 if (rc) {
2173 pr_warn("Failed to create SEV-SNP context, rc %d fw_error %d",
2174 rc, argp->error);
2175 snp_free_firmware_page(context);
2176 return NULL;
2177 }
2178
2179 return context;
2180 }
2181
snp_bind_asid(struct kvm * kvm,int * error)2182 static int snp_bind_asid(struct kvm *kvm, int *error)
2183 {
2184 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2185 struct sev_data_snp_activate data = {0};
2186
2187 data.gctx_paddr = __psp_pa(sev->snp_context);
2188 data.asid = sev_get_asid(kvm);
2189 return sev_issue_cmd(kvm, SEV_CMD_SNP_ACTIVATE, &data, error);
2190 }
2191
snp_launch_start(struct kvm * kvm,struct kvm_sev_cmd * argp)2192 static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
2193 {
2194 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2195 struct sev_data_snp_launch_start start = {0};
2196 struct kvm_sev_snp_launch_start params;
2197 int rc;
2198
2199 if (!sev_snp_guest(kvm))
2200 return -ENOTTY;
2201
2202 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
2203 return -EFAULT;
2204
2205 /* Don't allow userspace to allocate memory for more than 1 SNP context. */
2206 if (sev->snp_context)
2207 return -EINVAL;
2208
2209 if (params.flags)
2210 return -EINVAL;
2211
2212 if (params.policy & ~SNP_POLICY_MASK_VALID)
2213 return -EINVAL;
2214
2215 /* Check for policy bits that must be set */
2216 if (!(params.policy & SNP_POLICY_MASK_RSVD_MBO) ||
2217 !(params.policy & SNP_POLICY_MASK_SMT))
2218 return -EINVAL;
2219
2220 if (params.policy & SNP_POLICY_MASK_SINGLE_SOCKET)
2221 return -EINVAL;
2222
2223 sev->snp_context = snp_context_create(kvm, argp);
2224 if (!sev->snp_context)
2225 return -ENOTTY;
2226
2227 start.gctx_paddr = __psp_pa(sev->snp_context);
2228 start.policy = params.policy;
2229 memcpy(start.gosvw, params.gosvw, sizeof(params.gosvw));
2230 rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_START, &start, &argp->error);
2231 if (rc) {
2232 pr_debug("%s: SEV_CMD_SNP_LAUNCH_START firmware command failed, rc %d\n",
2233 __func__, rc);
2234 goto e_free_context;
2235 }
2236
2237 sev->fd = argp->sev_fd;
2238 rc = snp_bind_asid(kvm, &argp->error);
2239 if (rc) {
2240 pr_debug("%s: Failed to bind ASID to SEV-SNP context, rc %d\n",
2241 __func__, rc);
2242 goto e_free_context;
2243 }
2244
2245 return 0;
2246
2247 e_free_context:
2248 snp_decommission_context(kvm);
2249
2250 return rc;
2251 }
2252
2253 struct sev_gmem_populate_args {
2254 __u8 type;
2255 int sev_fd;
2256 int fw_error;
2257 };
2258
sev_gmem_post_populate(struct kvm * kvm,gfn_t gfn_start,kvm_pfn_t pfn,void __user * src,int order,void * opaque)2259 static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn_start, kvm_pfn_t pfn,
2260 void __user *src, int order, void *opaque)
2261 {
2262 struct sev_gmem_populate_args *sev_populate_args = opaque;
2263 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2264 int n_private = 0, ret, i;
2265 int npages = (1 << order);
2266 gfn_t gfn;
2267
2268 if (WARN_ON_ONCE(sev_populate_args->type != KVM_SEV_SNP_PAGE_TYPE_ZERO && !src))
2269 return -EINVAL;
2270
2271 for (gfn = gfn_start, i = 0; gfn < gfn_start + npages; gfn++, i++) {
2272 struct sev_data_snp_launch_update fw_args = {0};
2273 bool assigned = false;
2274 int level;
2275
2276 ret = snp_lookup_rmpentry((u64)pfn + i, &assigned, &level);
2277 if (ret || assigned) {
2278 pr_debug("%s: Failed to ensure GFN 0x%llx RMP entry is initial shared state, ret: %d assigned: %d\n",
2279 __func__, gfn, ret, assigned);
2280 ret = ret ? -EINVAL : -EEXIST;
2281 goto err;
2282 }
2283
2284 if (src) {
2285 void *vaddr = kmap_local_pfn(pfn + i);
2286
2287 if (copy_from_user(vaddr, src + i * PAGE_SIZE, PAGE_SIZE)) {
2288 ret = -EFAULT;
2289 goto err;
2290 }
2291 kunmap_local(vaddr);
2292 }
2293
2294 ret = rmp_make_private(pfn + i, gfn << PAGE_SHIFT, PG_LEVEL_4K,
2295 sev_get_asid(kvm), true);
2296 if (ret)
2297 goto err;
2298
2299 n_private++;
2300
2301 fw_args.gctx_paddr = __psp_pa(sev->snp_context);
2302 fw_args.address = __sme_set(pfn_to_hpa(pfn + i));
2303 fw_args.page_size = PG_LEVEL_TO_RMP(PG_LEVEL_4K);
2304 fw_args.page_type = sev_populate_args->type;
2305
2306 ret = __sev_issue_cmd(sev_populate_args->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
2307 &fw_args, &sev_populate_args->fw_error);
2308 if (ret)
2309 goto fw_err;
2310 }
2311
2312 return 0;
2313
2314 fw_err:
2315 /*
2316 * If the firmware command failed handle the reclaim and cleanup of that
2317 * PFN specially vs. prior pages which can be cleaned up below without
2318 * needing to reclaim in advance.
2319 *
2320 * Additionally, when invalid CPUID function entries are detected,
2321 * firmware writes the expected values into the page and leaves it
2322 * unencrypted so it can be used for debugging and error-reporting.
2323 *
2324 * Copy this page back into the source buffer so userspace can use this
2325 * information to provide information on which CPUID leaves/fields
2326 * failed CPUID validation.
2327 */
2328 if (!snp_page_reclaim(kvm, pfn + i) &&
2329 sev_populate_args->type == KVM_SEV_SNP_PAGE_TYPE_CPUID &&
2330 sev_populate_args->fw_error == SEV_RET_INVALID_PARAM) {
2331 void *vaddr = kmap_local_pfn(pfn + i);
2332
2333 if (copy_to_user(src + i * PAGE_SIZE, vaddr, PAGE_SIZE))
2334 pr_debug("Failed to write CPUID page back to userspace\n");
2335
2336 kunmap_local(vaddr);
2337 }
2338
2339 /* pfn + i is hypervisor-owned now, so skip below cleanup for it. */
2340 n_private--;
2341
2342 err:
2343 pr_debug("%s: exiting with error ret %d (fw_error %d), restoring %d gmem PFNs to shared.\n",
2344 __func__, ret, sev_populate_args->fw_error, n_private);
2345 for (i = 0; i < n_private; i++)
2346 kvm_rmp_make_shared(kvm, pfn + i, PG_LEVEL_4K);
2347
2348 return ret;
2349 }
2350
snp_launch_update(struct kvm * kvm,struct kvm_sev_cmd * argp)2351 static int snp_launch_update(struct kvm *kvm, struct kvm_sev_cmd *argp)
2352 {
2353 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2354 struct sev_gmem_populate_args sev_populate_args = {0};
2355 struct kvm_sev_snp_launch_update params;
2356 struct kvm_memory_slot *memslot;
2357 long npages, count;
2358 void __user *src;
2359 int ret = 0;
2360
2361 if (!sev_snp_guest(kvm) || !sev->snp_context)
2362 return -EINVAL;
2363
2364 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
2365 return -EFAULT;
2366
2367 pr_debug("%s: GFN start 0x%llx length 0x%llx type %d flags %d\n", __func__,
2368 params.gfn_start, params.len, params.type, params.flags);
2369
2370 if (!PAGE_ALIGNED(params.len) || params.flags ||
2371 (params.type != KVM_SEV_SNP_PAGE_TYPE_NORMAL &&
2372 params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO &&
2373 params.type != KVM_SEV_SNP_PAGE_TYPE_UNMEASURED &&
2374 params.type != KVM_SEV_SNP_PAGE_TYPE_SECRETS &&
2375 params.type != KVM_SEV_SNP_PAGE_TYPE_CPUID))
2376 return -EINVAL;
2377
2378 npages = params.len / PAGE_SIZE;
2379
2380 /*
2381 * For each GFN that's being prepared as part of the initial guest
2382 * state, the following pre-conditions are verified:
2383 *
2384 * 1) The backing memslot is a valid private memslot.
2385 * 2) The GFN has been set to private via KVM_SET_MEMORY_ATTRIBUTES
2386 * beforehand.
2387 * 3) The PFN of the guest_memfd has not already been set to private
2388 * in the RMP table.
2389 *
2390 * The KVM MMU relies on kvm->mmu_invalidate_seq to retry nested page
2391 * faults if there's a race between a fault and an attribute update via
2392 * KVM_SET_MEMORY_ATTRIBUTES, and a similar approach could be utilized
2393 * here. However, kvm->slots_lock guards against both this as well as
2394 * concurrent memslot updates occurring while these checks are being
2395 * performed, so use that here to make it easier to reason about the
2396 * initial expected state and better guard against unexpected
2397 * situations.
2398 */
2399 mutex_lock(&kvm->slots_lock);
2400
2401 memslot = gfn_to_memslot(kvm, params.gfn_start);
2402 if (!kvm_slot_can_be_private(memslot)) {
2403 ret = -EINVAL;
2404 goto out;
2405 }
2406
2407 sev_populate_args.sev_fd = argp->sev_fd;
2408 sev_populate_args.type = params.type;
2409 src = params.type == KVM_SEV_SNP_PAGE_TYPE_ZERO ? NULL : u64_to_user_ptr(params.uaddr);
2410
2411 count = kvm_gmem_populate(kvm, params.gfn_start, src, npages,
2412 sev_gmem_post_populate, &sev_populate_args);
2413 if (count < 0) {
2414 argp->error = sev_populate_args.fw_error;
2415 pr_debug("%s: kvm_gmem_populate failed, ret %ld (fw_error %d)\n",
2416 __func__, count, argp->error);
2417 ret = -EIO;
2418 } else {
2419 params.gfn_start += count;
2420 params.len -= count * PAGE_SIZE;
2421 if (params.type != KVM_SEV_SNP_PAGE_TYPE_ZERO)
2422 params.uaddr += count * PAGE_SIZE;
2423
2424 ret = 0;
2425 if (copy_to_user(u64_to_user_ptr(argp->data), ¶ms, sizeof(params)))
2426 ret = -EFAULT;
2427 }
2428
2429 out:
2430 mutex_unlock(&kvm->slots_lock);
2431
2432 return ret;
2433 }
2434
snp_launch_update_vmsa(struct kvm * kvm,struct kvm_sev_cmd * argp)2435 static int snp_launch_update_vmsa(struct kvm *kvm, struct kvm_sev_cmd *argp)
2436 {
2437 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2438 struct sev_data_snp_launch_update data = {};
2439 struct kvm_vcpu *vcpu;
2440 unsigned long i;
2441 int ret;
2442
2443 data.gctx_paddr = __psp_pa(sev->snp_context);
2444 data.page_type = SNP_PAGE_TYPE_VMSA;
2445
2446 kvm_for_each_vcpu(i, vcpu, kvm) {
2447 struct vcpu_svm *svm = to_svm(vcpu);
2448 u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
2449
2450 ret = sev_es_sync_vmsa(svm);
2451 if (ret)
2452 return ret;
2453
2454 /* Transition the VMSA page to a firmware state. */
2455 ret = rmp_make_private(pfn, INITIAL_VMSA_GPA, PG_LEVEL_4K, sev->asid, true);
2456 if (ret)
2457 return ret;
2458
2459 /* Issue the SNP command to encrypt the VMSA */
2460 data.address = __sme_pa(svm->sev_es.vmsa);
2461 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_LAUNCH_UPDATE,
2462 &data, &argp->error);
2463 if (ret) {
2464 snp_page_reclaim(kvm, pfn);
2465
2466 return ret;
2467 }
2468
2469 svm->vcpu.arch.guest_state_protected = true;
2470 /*
2471 * SEV-ES (and thus SNP) guest mandates LBR Virtualization to
2472 * be _always_ ON. Enable it only after setting
2473 * guest_state_protected because KVM_SET_MSRS allows dynamic
2474 * toggling of LBRV (for performance reason) on write access to
2475 * MSR_IA32_DEBUGCTLMSR when guest_state_protected is not set.
2476 */
2477 svm_enable_lbrv(vcpu);
2478 }
2479
2480 return 0;
2481 }
2482
snp_launch_finish(struct kvm * kvm,struct kvm_sev_cmd * argp)2483 static int snp_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
2484 {
2485 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2486 struct kvm_sev_snp_launch_finish params;
2487 struct sev_data_snp_launch_finish *data;
2488 void *id_block = NULL, *id_auth = NULL;
2489 int ret;
2490
2491 if (!sev_snp_guest(kvm))
2492 return -ENOTTY;
2493
2494 if (!sev->snp_context)
2495 return -EINVAL;
2496
2497 if (copy_from_user(¶ms, u64_to_user_ptr(argp->data), sizeof(params)))
2498 return -EFAULT;
2499
2500 if (params.flags)
2501 return -EINVAL;
2502
2503 /* Measure all vCPUs using LAUNCH_UPDATE before finalizing the launch flow. */
2504 ret = snp_launch_update_vmsa(kvm, argp);
2505 if (ret)
2506 return ret;
2507
2508 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
2509 if (!data)
2510 return -ENOMEM;
2511
2512 if (params.id_block_en) {
2513 id_block = psp_copy_user_blob(params.id_block_uaddr, KVM_SEV_SNP_ID_BLOCK_SIZE);
2514 if (IS_ERR(id_block)) {
2515 ret = PTR_ERR(id_block);
2516 goto e_free;
2517 }
2518
2519 data->id_block_en = 1;
2520 data->id_block_paddr = __sme_pa(id_block);
2521
2522 id_auth = psp_copy_user_blob(params.id_auth_uaddr, KVM_SEV_SNP_ID_AUTH_SIZE);
2523 if (IS_ERR(id_auth)) {
2524 ret = PTR_ERR(id_auth);
2525 goto e_free_id_block;
2526 }
2527
2528 data->id_auth_paddr = __sme_pa(id_auth);
2529
2530 if (params.auth_key_en)
2531 data->auth_key_en = 1;
2532 }
2533
2534 data->vcek_disabled = params.vcek_disabled;
2535
2536 memcpy(data->host_data, params.host_data, KVM_SEV_SNP_FINISH_DATA_SIZE);
2537 data->gctx_paddr = __psp_pa(sev->snp_context);
2538 ret = sev_issue_cmd(kvm, SEV_CMD_SNP_LAUNCH_FINISH, data, &argp->error);
2539
2540 /*
2541 * Now that there will be no more SNP_LAUNCH_UPDATE ioctls, private pages
2542 * can be given to the guest simply by marking the RMP entry as private.
2543 * This can happen on first access and also with KVM_PRE_FAULT_MEMORY.
2544 */
2545 if (!ret)
2546 kvm->arch.pre_fault_allowed = true;
2547
2548 kfree(id_auth);
2549
2550 e_free_id_block:
2551 kfree(id_block);
2552
2553 e_free:
2554 kfree(data);
2555
2556 return ret;
2557 }
2558
sev_mem_enc_ioctl(struct kvm * kvm,void __user * argp)2559 int sev_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
2560 {
2561 struct kvm_sev_cmd sev_cmd;
2562 int r;
2563
2564 if (!sev_enabled)
2565 return -ENOTTY;
2566
2567 if (!argp)
2568 return 0;
2569
2570 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
2571 return -EFAULT;
2572
2573 mutex_lock(&kvm->lock);
2574
2575 /* Only the enc_context_owner handles some memory enc operations. */
2576 if (is_mirroring_enc_context(kvm) &&
2577 !is_cmd_allowed_from_mirror(sev_cmd.id)) {
2578 r = -EINVAL;
2579 goto out;
2580 }
2581
2582 /*
2583 * Once KVM_SEV_INIT2 initializes a KVM instance as an SNP guest, only
2584 * allow the use of SNP-specific commands.
2585 */
2586 if (sev_snp_guest(kvm) && sev_cmd.id < KVM_SEV_SNP_LAUNCH_START) {
2587 r = -EPERM;
2588 goto out;
2589 }
2590
2591 switch (sev_cmd.id) {
2592 case KVM_SEV_ES_INIT:
2593 if (!sev_es_enabled) {
2594 r = -ENOTTY;
2595 goto out;
2596 }
2597 fallthrough;
2598 case KVM_SEV_INIT:
2599 r = sev_guest_init(kvm, &sev_cmd);
2600 break;
2601 case KVM_SEV_INIT2:
2602 r = sev_guest_init2(kvm, &sev_cmd);
2603 break;
2604 case KVM_SEV_LAUNCH_START:
2605 r = sev_launch_start(kvm, &sev_cmd);
2606 break;
2607 case KVM_SEV_LAUNCH_UPDATE_DATA:
2608 r = sev_launch_update_data(kvm, &sev_cmd);
2609 break;
2610 case KVM_SEV_LAUNCH_UPDATE_VMSA:
2611 r = sev_launch_update_vmsa(kvm, &sev_cmd);
2612 break;
2613 case KVM_SEV_LAUNCH_MEASURE:
2614 r = sev_launch_measure(kvm, &sev_cmd);
2615 break;
2616 case KVM_SEV_LAUNCH_FINISH:
2617 r = sev_launch_finish(kvm, &sev_cmd);
2618 break;
2619 case KVM_SEV_GUEST_STATUS:
2620 r = sev_guest_status(kvm, &sev_cmd);
2621 break;
2622 case KVM_SEV_DBG_DECRYPT:
2623 r = sev_dbg_crypt(kvm, &sev_cmd, true);
2624 break;
2625 case KVM_SEV_DBG_ENCRYPT:
2626 r = sev_dbg_crypt(kvm, &sev_cmd, false);
2627 break;
2628 case KVM_SEV_LAUNCH_SECRET:
2629 r = sev_launch_secret(kvm, &sev_cmd);
2630 break;
2631 case KVM_SEV_GET_ATTESTATION_REPORT:
2632 r = sev_get_attestation_report(kvm, &sev_cmd);
2633 break;
2634 case KVM_SEV_SEND_START:
2635 r = sev_send_start(kvm, &sev_cmd);
2636 break;
2637 case KVM_SEV_SEND_UPDATE_DATA:
2638 r = sev_send_update_data(kvm, &sev_cmd);
2639 break;
2640 case KVM_SEV_SEND_FINISH:
2641 r = sev_send_finish(kvm, &sev_cmd);
2642 break;
2643 case KVM_SEV_SEND_CANCEL:
2644 r = sev_send_cancel(kvm, &sev_cmd);
2645 break;
2646 case KVM_SEV_RECEIVE_START:
2647 r = sev_receive_start(kvm, &sev_cmd);
2648 break;
2649 case KVM_SEV_RECEIVE_UPDATE_DATA:
2650 r = sev_receive_update_data(kvm, &sev_cmd);
2651 break;
2652 case KVM_SEV_RECEIVE_FINISH:
2653 r = sev_receive_finish(kvm, &sev_cmd);
2654 break;
2655 case KVM_SEV_SNP_LAUNCH_START:
2656 r = snp_launch_start(kvm, &sev_cmd);
2657 break;
2658 case KVM_SEV_SNP_LAUNCH_UPDATE:
2659 r = snp_launch_update(kvm, &sev_cmd);
2660 break;
2661 case KVM_SEV_SNP_LAUNCH_FINISH:
2662 r = snp_launch_finish(kvm, &sev_cmd);
2663 break;
2664 default:
2665 r = -EINVAL;
2666 goto out;
2667 }
2668
2669 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
2670 r = -EFAULT;
2671
2672 out:
2673 mutex_unlock(&kvm->lock);
2674 return r;
2675 }
2676
sev_mem_enc_register_region(struct kvm * kvm,struct kvm_enc_region * range)2677 int sev_mem_enc_register_region(struct kvm *kvm,
2678 struct kvm_enc_region *range)
2679 {
2680 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2681 struct enc_region *region;
2682 int ret = 0;
2683
2684 if (!sev_guest(kvm))
2685 return -ENOTTY;
2686
2687 /* If kvm is mirroring encryption context it isn't responsible for it */
2688 if (is_mirroring_enc_context(kvm))
2689 return -EINVAL;
2690
2691 if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
2692 return -EINVAL;
2693
2694 region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
2695 if (!region)
2696 return -ENOMEM;
2697
2698 mutex_lock(&kvm->lock);
2699 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
2700 if (IS_ERR(region->pages)) {
2701 ret = PTR_ERR(region->pages);
2702 mutex_unlock(&kvm->lock);
2703 goto e_free;
2704 }
2705
2706 /*
2707 * The guest may change the memory encryption attribute from C=0 -> C=1
2708 * or vice versa for this memory range. Lets make sure caches are
2709 * flushed to ensure that guest data gets written into memory with
2710 * correct C-bit. Note, this must be done before dropping kvm->lock,
2711 * as region and its array of pages can be freed by a different task
2712 * once kvm->lock is released.
2713 */
2714 sev_clflush_pages(region->pages, region->npages);
2715
2716 region->uaddr = range->addr;
2717 region->size = range->size;
2718
2719 list_add_tail(®ion->list, &sev->regions_list);
2720 mutex_unlock(&kvm->lock);
2721
2722 return ret;
2723
2724 e_free:
2725 kfree(region);
2726 return ret;
2727 }
2728
2729 static struct enc_region *
find_enc_region(struct kvm * kvm,struct kvm_enc_region * range)2730 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
2731 {
2732 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2733 struct list_head *head = &sev->regions_list;
2734 struct enc_region *i;
2735
2736 list_for_each_entry(i, head, list) {
2737 if (i->uaddr == range->addr &&
2738 i->size == range->size)
2739 return i;
2740 }
2741
2742 return NULL;
2743 }
2744
__unregister_enc_region_locked(struct kvm * kvm,struct enc_region * region)2745 static void __unregister_enc_region_locked(struct kvm *kvm,
2746 struct enc_region *region)
2747 {
2748 sev_unpin_memory(kvm, region->pages, region->npages);
2749 list_del(®ion->list);
2750 kfree(region);
2751 }
2752
sev_mem_enc_unregister_region(struct kvm * kvm,struct kvm_enc_region * range)2753 int sev_mem_enc_unregister_region(struct kvm *kvm,
2754 struct kvm_enc_region *range)
2755 {
2756 struct enc_region *region;
2757 int ret;
2758
2759 /* If kvm is mirroring encryption context it isn't responsible for it */
2760 if (is_mirroring_enc_context(kvm))
2761 return -EINVAL;
2762
2763 mutex_lock(&kvm->lock);
2764
2765 if (!sev_guest(kvm)) {
2766 ret = -ENOTTY;
2767 goto failed;
2768 }
2769
2770 region = find_enc_region(kvm, range);
2771 if (!region) {
2772 ret = -EINVAL;
2773 goto failed;
2774 }
2775
2776 /*
2777 * Ensure that all guest tagged cache entries are flushed before
2778 * releasing the pages back to the system for use. CLFLUSH will
2779 * not do this, so issue a WBINVD.
2780 */
2781 wbinvd_on_all_cpus();
2782
2783 __unregister_enc_region_locked(kvm, region);
2784
2785 mutex_unlock(&kvm->lock);
2786 return 0;
2787
2788 failed:
2789 mutex_unlock(&kvm->lock);
2790 return ret;
2791 }
2792
sev_vm_copy_enc_context_from(struct kvm * kvm,unsigned int source_fd)2793 int sev_vm_copy_enc_context_from(struct kvm *kvm, unsigned int source_fd)
2794 {
2795 CLASS(fd, f)(source_fd);
2796 struct kvm *source_kvm;
2797 struct kvm_sev_info *source_sev, *mirror_sev;
2798 int ret;
2799
2800 if (fd_empty(f))
2801 return -EBADF;
2802
2803 if (!file_is_kvm(fd_file(f)))
2804 return -EBADF;
2805
2806 source_kvm = fd_file(f)->private_data;
2807 ret = sev_lock_two_vms(kvm, source_kvm);
2808 if (ret)
2809 return ret;
2810
2811 /*
2812 * Mirrors of mirrors should work, but let's not get silly. Also
2813 * disallow out-of-band SEV/SEV-ES init if the target is already an
2814 * SEV guest, or if vCPUs have been created. KVM relies on vCPUs being
2815 * created after SEV/SEV-ES initialization, e.g. to init intercepts.
2816 */
2817 if (sev_guest(kvm) || !sev_guest(source_kvm) ||
2818 is_mirroring_enc_context(source_kvm) || kvm->created_vcpus) {
2819 ret = -EINVAL;
2820 goto e_unlock;
2821 }
2822
2823 /*
2824 * The mirror kvm holds an enc_context_owner ref so its asid can't
2825 * disappear until we're done with it
2826 */
2827 source_sev = &to_kvm_svm(source_kvm)->sev_info;
2828 kvm_get_kvm(source_kvm);
2829 mirror_sev = &to_kvm_svm(kvm)->sev_info;
2830 list_add_tail(&mirror_sev->mirror_entry, &source_sev->mirror_vms);
2831
2832 /* Set enc_context_owner and copy its encryption context over */
2833 mirror_sev->enc_context_owner = source_kvm;
2834 mirror_sev->active = true;
2835 mirror_sev->asid = source_sev->asid;
2836 mirror_sev->fd = source_sev->fd;
2837 mirror_sev->es_active = source_sev->es_active;
2838 mirror_sev->need_init = false;
2839 mirror_sev->handle = source_sev->handle;
2840 INIT_LIST_HEAD(&mirror_sev->regions_list);
2841 INIT_LIST_HEAD(&mirror_sev->mirror_vms);
2842 ret = 0;
2843
2844 /*
2845 * Do not copy ap_jump_table. Since the mirror does not share the same
2846 * KVM contexts as the original, and they may have different
2847 * memory-views.
2848 */
2849
2850 e_unlock:
2851 sev_unlock_two_vms(kvm, source_kvm);
2852 return ret;
2853 }
2854
snp_decommission_context(struct kvm * kvm)2855 static int snp_decommission_context(struct kvm *kvm)
2856 {
2857 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2858 struct sev_data_snp_addr data = {};
2859 int ret;
2860
2861 /* If context is not created then do nothing */
2862 if (!sev->snp_context)
2863 return 0;
2864
2865 /* Do the decommision, which will unbind the ASID from the SNP context */
2866 data.address = __sme_pa(sev->snp_context);
2867 down_write(&sev_deactivate_lock);
2868 ret = sev_do_cmd(SEV_CMD_SNP_DECOMMISSION, &data, NULL);
2869 up_write(&sev_deactivate_lock);
2870
2871 if (WARN_ONCE(ret, "Failed to release guest context, ret %d", ret))
2872 return ret;
2873
2874 snp_free_firmware_page(sev->snp_context);
2875 sev->snp_context = NULL;
2876
2877 return 0;
2878 }
2879
sev_vm_destroy(struct kvm * kvm)2880 void sev_vm_destroy(struct kvm *kvm)
2881 {
2882 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2883 struct list_head *head = &sev->regions_list;
2884 struct list_head *pos, *q;
2885
2886 if (!sev_guest(kvm))
2887 return;
2888
2889 WARN_ON(!list_empty(&sev->mirror_vms));
2890
2891 /* If this is a mirror_kvm release the enc_context_owner and skip sev cleanup */
2892 if (is_mirroring_enc_context(kvm)) {
2893 struct kvm *owner_kvm = sev->enc_context_owner;
2894
2895 mutex_lock(&owner_kvm->lock);
2896 list_del(&sev->mirror_entry);
2897 mutex_unlock(&owner_kvm->lock);
2898 kvm_put_kvm(owner_kvm);
2899 return;
2900 }
2901
2902 /*
2903 * Ensure that all guest tagged cache entries are flushed before
2904 * releasing the pages back to the system for use. CLFLUSH will
2905 * not do this, so issue a WBINVD.
2906 */
2907 wbinvd_on_all_cpus();
2908
2909 /*
2910 * if userspace was terminated before unregistering the memory regions
2911 * then lets unpin all the registered memory.
2912 */
2913 if (!list_empty(head)) {
2914 list_for_each_safe(pos, q, head) {
2915 __unregister_enc_region_locked(kvm,
2916 list_entry(pos, struct enc_region, list));
2917 cond_resched();
2918 }
2919 }
2920
2921 if (sev_snp_guest(kvm)) {
2922 snp_guest_req_cleanup(kvm);
2923
2924 /*
2925 * Decomission handles unbinding of the ASID. If it fails for
2926 * some unexpected reason, just leak the ASID.
2927 */
2928 if (snp_decommission_context(kvm))
2929 return;
2930 } else {
2931 sev_unbind_asid(kvm, sev->handle);
2932 }
2933
2934 sev_asid_free(sev);
2935 }
2936
sev_set_cpu_caps(void)2937 void __init sev_set_cpu_caps(void)
2938 {
2939 if (sev_enabled) {
2940 kvm_cpu_cap_set(X86_FEATURE_SEV);
2941 kvm_caps.supported_vm_types |= BIT(KVM_X86_SEV_VM);
2942 }
2943 if (sev_es_enabled) {
2944 kvm_cpu_cap_set(X86_FEATURE_SEV_ES);
2945 kvm_caps.supported_vm_types |= BIT(KVM_X86_SEV_ES_VM);
2946 }
2947 if (sev_snp_enabled) {
2948 kvm_cpu_cap_set(X86_FEATURE_SEV_SNP);
2949 kvm_caps.supported_vm_types |= BIT(KVM_X86_SNP_VM);
2950 }
2951 }
2952
sev_hardware_setup(void)2953 void __init sev_hardware_setup(void)
2954 {
2955 unsigned int eax, ebx, ecx, edx, sev_asid_count, sev_es_asid_count;
2956 bool sev_snp_supported = false;
2957 bool sev_es_supported = false;
2958 bool sev_supported = false;
2959
2960 if (!sev_enabled || !npt_enabled || !nrips)
2961 goto out;
2962
2963 /*
2964 * SEV must obviously be supported in hardware. Sanity check that the
2965 * CPU supports decode assists, which is mandatory for SEV guests to
2966 * support instruction emulation. Ditto for flushing by ASID, as SEV
2967 * guests are bound to a single ASID, i.e. KVM can't rotate to a new
2968 * ASID to effect a TLB flush.
2969 */
2970 if (!boot_cpu_has(X86_FEATURE_SEV) ||
2971 WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_DECODEASSISTS)) ||
2972 WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_FLUSHBYASID)))
2973 goto out;
2974
2975 /*
2976 * The kernel's initcall infrastructure lacks the ability to express
2977 * dependencies between initcalls, whereas the modules infrastructure
2978 * automatically handles dependencies via symbol loading. Ensure the
2979 * PSP SEV driver is initialized before proceeding if KVM is built-in,
2980 * as the dependency isn't handled by the initcall infrastructure.
2981 */
2982 if (IS_BUILTIN(CONFIG_KVM_AMD) && sev_module_init())
2983 goto out;
2984
2985 /* Retrieve SEV CPUID information */
2986 cpuid(0x8000001f, &eax, &ebx, &ecx, &edx);
2987
2988 /* Set encryption bit location for SEV-ES guests */
2989 sev_enc_bit = ebx & 0x3f;
2990
2991 /* Maximum number of encrypted guests supported simultaneously */
2992 max_sev_asid = ecx;
2993 if (!max_sev_asid)
2994 goto out;
2995
2996 /* Minimum ASID value that should be used for SEV guest */
2997 min_sev_asid = edx;
2998 sev_me_mask = 1UL << (ebx & 0x3f);
2999
3000 /*
3001 * Initialize SEV ASID bitmaps. Allocate space for ASID 0 in the bitmap,
3002 * even though it's never used, so that the bitmap is indexed by the
3003 * actual ASID.
3004 */
3005 nr_asids = max_sev_asid + 1;
3006 sev_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
3007 if (!sev_asid_bitmap)
3008 goto out;
3009
3010 sev_reclaim_asid_bitmap = bitmap_zalloc(nr_asids, GFP_KERNEL);
3011 if (!sev_reclaim_asid_bitmap) {
3012 bitmap_free(sev_asid_bitmap);
3013 sev_asid_bitmap = NULL;
3014 goto out;
3015 }
3016
3017 if (min_sev_asid <= max_sev_asid) {
3018 sev_asid_count = max_sev_asid - min_sev_asid + 1;
3019 WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV, sev_asid_count));
3020 }
3021 sev_supported = true;
3022
3023 /* SEV-ES support requested? */
3024 if (!sev_es_enabled)
3025 goto out;
3026
3027 /*
3028 * SEV-ES requires MMIO caching as KVM doesn't have access to the guest
3029 * instruction stream, i.e. can't emulate in response to a #NPF and
3030 * instead relies on #NPF(RSVD) being reflected into the guest as #VC
3031 * (the guest can then do a #VMGEXIT to request MMIO emulation).
3032 */
3033 if (!enable_mmio_caching)
3034 goto out;
3035
3036 /* Does the CPU support SEV-ES? */
3037 if (!boot_cpu_has(X86_FEATURE_SEV_ES))
3038 goto out;
3039
3040 if (!lbrv) {
3041 WARN_ONCE(!boot_cpu_has(X86_FEATURE_LBRV),
3042 "LBRV must be present for SEV-ES support");
3043 goto out;
3044 }
3045
3046 /* Has the system been allocated ASIDs for SEV-ES? */
3047 if (min_sev_asid == 1)
3048 goto out;
3049
3050 sev_es_asid_count = min_sev_asid - 1;
3051 WARN_ON_ONCE(misc_cg_set_capacity(MISC_CG_RES_SEV_ES, sev_es_asid_count));
3052 sev_es_supported = true;
3053 sev_snp_supported = sev_snp_enabled && cc_platform_has(CC_ATTR_HOST_SEV_SNP);
3054
3055 out:
3056 if (boot_cpu_has(X86_FEATURE_SEV))
3057 pr_info("SEV %s (ASIDs %u - %u)\n",
3058 sev_supported ? min_sev_asid <= max_sev_asid ? "enabled" :
3059 "unusable" :
3060 "disabled",
3061 min_sev_asid, max_sev_asid);
3062 if (boot_cpu_has(X86_FEATURE_SEV_ES))
3063 pr_info("SEV-ES %s (ASIDs %u - %u)\n",
3064 str_enabled_disabled(sev_es_supported),
3065 min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1);
3066 if (boot_cpu_has(X86_FEATURE_SEV_SNP))
3067 pr_info("SEV-SNP %s (ASIDs %u - %u)\n",
3068 str_enabled_disabled(sev_snp_supported),
3069 min_sev_asid > 1 ? 1 : 0, min_sev_asid - 1);
3070
3071 sev_enabled = sev_supported;
3072 sev_es_enabled = sev_es_supported;
3073 sev_snp_enabled = sev_snp_supported;
3074
3075 if (!sev_es_enabled || !cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP) ||
3076 !cpu_feature_enabled(X86_FEATURE_NO_NESTED_DATA_BP))
3077 sev_es_debug_swap_enabled = false;
3078
3079 sev_supported_vmsa_features = 0;
3080 if (sev_es_debug_swap_enabled)
3081 sev_supported_vmsa_features |= SVM_SEV_FEAT_DEBUG_SWAP;
3082 }
3083
sev_hardware_unsetup(void)3084 void sev_hardware_unsetup(void)
3085 {
3086 if (!sev_enabled)
3087 return;
3088
3089 /* No need to take sev_bitmap_lock, all VMs have been destroyed. */
3090 sev_flush_asids(1, max_sev_asid);
3091
3092 bitmap_free(sev_asid_bitmap);
3093 bitmap_free(sev_reclaim_asid_bitmap);
3094
3095 misc_cg_set_capacity(MISC_CG_RES_SEV, 0);
3096 misc_cg_set_capacity(MISC_CG_RES_SEV_ES, 0);
3097 }
3098
sev_cpu_init(struct svm_cpu_data * sd)3099 int sev_cpu_init(struct svm_cpu_data *sd)
3100 {
3101 if (!sev_enabled)
3102 return 0;
3103
3104 sd->sev_vmcbs = kcalloc(nr_asids, sizeof(void *), GFP_KERNEL);
3105 if (!sd->sev_vmcbs)
3106 return -ENOMEM;
3107
3108 return 0;
3109 }
3110
3111 /*
3112 * Pages used by hardware to hold guest encrypted state must be flushed before
3113 * returning them to the system.
3114 */
sev_flush_encrypted_page(struct kvm_vcpu * vcpu,void * va)3115 static void sev_flush_encrypted_page(struct kvm_vcpu *vcpu, void *va)
3116 {
3117 unsigned int asid = sev_get_asid(vcpu->kvm);
3118
3119 /*
3120 * Note! The address must be a kernel address, as regular page walk
3121 * checks are performed by VM_PAGE_FLUSH, i.e. operating on a user
3122 * address is non-deterministic and unsafe. This function deliberately
3123 * takes a pointer to deter passing in a user address.
3124 */
3125 unsigned long addr = (unsigned long)va;
3126
3127 /*
3128 * If CPU enforced cache coherency for encrypted mappings of the
3129 * same physical page is supported, use CLFLUSHOPT instead. NOTE: cache
3130 * flush is still needed in order to work properly with DMA devices.
3131 */
3132 if (boot_cpu_has(X86_FEATURE_SME_COHERENT)) {
3133 clflush_cache_range(va, PAGE_SIZE);
3134 return;
3135 }
3136
3137 /*
3138 * VM Page Flush takes a host virtual address and a guest ASID. Fall
3139 * back to WBINVD if this faults so as not to make any problems worse
3140 * by leaving stale encrypted data in the cache.
3141 */
3142 if (WARN_ON_ONCE(wrmsrl_safe(MSR_AMD64_VM_PAGE_FLUSH, addr | asid)))
3143 goto do_wbinvd;
3144
3145 return;
3146
3147 do_wbinvd:
3148 wbinvd_on_all_cpus();
3149 }
3150
sev_guest_memory_reclaimed(struct kvm * kvm)3151 void sev_guest_memory_reclaimed(struct kvm *kvm)
3152 {
3153 /*
3154 * With SNP+gmem, private/encrypted memory is unreachable via the
3155 * hva-based mmu notifiers, so these events are only actually
3156 * pertaining to shared pages where there is no need to perform
3157 * the WBINVD to flush associated caches.
3158 */
3159 if (!sev_guest(kvm) || sev_snp_guest(kvm))
3160 return;
3161
3162 wbinvd_on_all_cpus();
3163 }
3164
sev_free_vcpu(struct kvm_vcpu * vcpu)3165 void sev_free_vcpu(struct kvm_vcpu *vcpu)
3166 {
3167 struct vcpu_svm *svm;
3168
3169 if (!sev_es_guest(vcpu->kvm))
3170 return;
3171
3172 svm = to_svm(vcpu);
3173
3174 /*
3175 * If it's an SNP guest, then the VMSA was marked in the RMP table as
3176 * a guest-owned page. Transition the page to hypervisor state before
3177 * releasing it back to the system.
3178 */
3179 if (sev_snp_guest(vcpu->kvm)) {
3180 u64 pfn = __pa(svm->sev_es.vmsa) >> PAGE_SHIFT;
3181
3182 if (kvm_rmp_make_shared(vcpu->kvm, pfn, PG_LEVEL_4K))
3183 goto skip_vmsa_free;
3184 }
3185
3186 if (vcpu->arch.guest_state_protected)
3187 sev_flush_encrypted_page(vcpu, svm->sev_es.vmsa);
3188
3189 __free_page(virt_to_page(svm->sev_es.vmsa));
3190
3191 skip_vmsa_free:
3192 if (svm->sev_es.ghcb_sa_free)
3193 kvfree(svm->sev_es.ghcb_sa);
3194 }
3195
dump_ghcb(struct vcpu_svm * svm)3196 static void dump_ghcb(struct vcpu_svm *svm)
3197 {
3198 struct ghcb *ghcb = svm->sev_es.ghcb;
3199 unsigned int nbits;
3200
3201 /* Re-use the dump_invalid_vmcb module parameter */
3202 if (!dump_invalid_vmcb) {
3203 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3204 return;
3205 }
3206
3207 nbits = sizeof(ghcb->save.valid_bitmap) * 8;
3208
3209 pr_err("GHCB (GPA=%016llx):\n", svm->vmcb->control.ghcb_gpa);
3210 pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_code",
3211 ghcb->save.sw_exit_code, ghcb_sw_exit_code_is_valid(ghcb));
3212 pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_1",
3213 ghcb->save.sw_exit_info_1, ghcb_sw_exit_info_1_is_valid(ghcb));
3214 pr_err("%-20s%016llx is_valid: %u\n", "sw_exit_info_2",
3215 ghcb->save.sw_exit_info_2, ghcb_sw_exit_info_2_is_valid(ghcb));
3216 pr_err("%-20s%016llx is_valid: %u\n", "sw_scratch",
3217 ghcb->save.sw_scratch, ghcb_sw_scratch_is_valid(ghcb));
3218 pr_err("%-20s%*pb\n", "valid_bitmap", nbits, ghcb->save.valid_bitmap);
3219 }
3220
sev_es_sync_to_ghcb(struct vcpu_svm * svm)3221 static void sev_es_sync_to_ghcb(struct vcpu_svm *svm)
3222 {
3223 struct kvm_vcpu *vcpu = &svm->vcpu;
3224 struct ghcb *ghcb = svm->sev_es.ghcb;
3225
3226 /*
3227 * The GHCB protocol so far allows for the following data
3228 * to be returned:
3229 * GPRs RAX, RBX, RCX, RDX
3230 *
3231 * Copy their values, even if they may not have been written during the
3232 * VM-Exit. It's the guest's responsibility to not consume random data.
3233 */
3234 ghcb_set_rax(ghcb, vcpu->arch.regs[VCPU_REGS_RAX]);
3235 ghcb_set_rbx(ghcb, vcpu->arch.regs[VCPU_REGS_RBX]);
3236 ghcb_set_rcx(ghcb, vcpu->arch.regs[VCPU_REGS_RCX]);
3237 ghcb_set_rdx(ghcb, vcpu->arch.regs[VCPU_REGS_RDX]);
3238 }
3239
sev_es_sync_from_ghcb(struct vcpu_svm * svm)3240 static void sev_es_sync_from_ghcb(struct vcpu_svm *svm)
3241 {
3242 struct vmcb_control_area *control = &svm->vmcb->control;
3243 struct kvm_vcpu *vcpu = &svm->vcpu;
3244 struct ghcb *ghcb = svm->sev_es.ghcb;
3245 u64 exit_code;
3246
3247 /*
3248 * The GHCB protocol so far allows for the following data
3249 * to be supplied:
3250 * GPRs RAX, RBX, RCX, RDX
3251 * XCR0
3252 * CPL
3253 *
3254 * VMMCALL allows the guest to provide extra registers. KVM also
3255 * expects RSI for hypercalls, so include that, too.
3256 *
3257 * Copy their values to the appropriate location if supplied.
3258 */
3259 memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
3260
3261 BUILD_BUG_ON(sizeof(svm->sev_es.valid_bitmap) != sizeof(ghcb->save.valid_bitmap));
3262 memcpy(&svm->sev_es.valid_bitmap, &ghcb->save.valid_bitmap, sizeof(ghcb->save.valid_bitmap));
3263
3264 vcpu->arch.regs[VCPU_REGS_RAX] = kvm_ghcb_get_rax_if_valid(svm, ghcb);
3265 vcpu->arch.regs[VCPU_REGS_RBX] = kvm_ghcb_get_rbx_if_valid(svm, ghcb);
3266 vcpu->arch.regs[VCPU_REGS_RCX] = kvm_ghcb_get_rcx_if_valid(svm, ghcb);
3267 vcpu->arch.regs[VCPU_REGS_RDX] = kvm_ghcb_get_rdx_if_valid(svm, ghcb);
3268 vcpu->arch.regs[VCPU_REGS_RSI] = kvm_ghcb_get_rsi_if_valid(svm, ghcb);
3269
3270 svm->vmcb->save.cpl = kvm_ghcb_get_cpl_if_valid(svm, ghcb);
3271
3272 if (kvm_ghcb_xcr0_is_valid(svm)) {
3273 vcpu->arch.xcr0 = ghcb_get_xcr0(ghcb);
3274 kvm_update_cpuid_runtime(vcpu);
3275 }
3276
3277 /* Copy the GHCB exit information into the VMCB fields */
3278 exit_code = ghcb_get_sw_exit_code(ghcb);
3279 control->exit_code = lower_32_bits(exit_code);
3280 control->exit_code_hi = upper_32_bits(exit_code);
3281 control->exit_info_1 = ghcb_get_sw_exit_info_1(ghcb);
3282 control->exit_info_2 = ghcb_get_sw_exit_info_2(ghcb);
3283 svm->sev_es.sw_scratch = kvm_ghcb_get_sw_scratch_if_valid(svm, ghcb);
3284
3285 /* Clear the valid entries fields */
3286 memset(ghcb->save.valid_bitmap, 0, sizeof(ghcb->save.valid_bitmap));
3287 }
3288
kvm_ghcb_get_sw_exit_code(struct vmcb_control_area * control)3289 static u64 kvm_ghcb_get_sw_exit_code(struct vmcb_control_area *control)
3290 {
3291 return (((u64)control->exit_code_hi) << 32) | control->exit_code;
3292 }
3293
sev_es_validate_vmgexit(struct vcpu_svm * svm)3294 static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
3295 {
3296 struct vmcb_control_area *control = &svm->vmcb->control;
3297 struct kvm_vcpu *vcpu = &svm->vcpu;
3298 u64 exit_code;
3299 u64 reason;
3300
3301 /*
3302 * Retrieve the exit code now even though it may not be marked valid
3303 * as it could help with debugging.
3304 */
3305 exit_code = kvm_ghcb_get_sw_exit_code(control);
3306
3307 /* Only GHCB Usage code 0 is supported */
3308 if (svm->sev_es.ghcb->ghcb_usage) {
3309 reason = GHCB_ERR_INVALID_USAGE;
3310 goto vmgexit_err;
3311 }
3312
3313 reason = GHCB_ERR_MISSING_INPUT;
3314
3315 if (!kvm_ghcb_sw_exit_code_is_valid(svm) ||
3316 !kvm_ghcb_sw_exit_info_1_is_valid(svm) ||
3317 !kvm_ghcb_sw_exit_info_2_is_valid(svm))
3318 goto vmgexit_err;
3319
3320 switch (exit_code) {
3321 case SVM_EXIT_READ_DR7:
3322 break;
3323 case SVM_EXIT_WRITE_DR7:
3324 if (!kvm_ghcb_rax_is_valid(svm))
3325 goto vmgexit_err;
3326 break;
3327 case SVM_EXIT_RDTSC:
3328 break;
3329 case SVM_EXIT_RDPMC:
3330 if (!kvm_ghcb_rcx_is_valid(svm))
3331 goto vmgexit_err;
3332 break;
3333 case SVM_EXIT_CPUID:
3334 if (!kvm_ghcb_rax_is_valid(svm) ||
3335 !kvm_ghcb_rcx_is_valid(svm))
3336 goto vmgexit_err;
3337 if (vcpu->arch.regs[VCPU_REGS_RAX] == 0xd)
3338 if (!kvm_ghcb_xcr0_is_valid(svm))
3339 goto vmgexit_err;
3340 break;
3341 case SVM_EXIT_INVD:
3342 break;
3343 case SVM_EXIT_IOIO:
3344 if (control->exit_info_1 & SVM_IOIO_STR_MASK) {
3345 if (!kvm_ghcb_sw_scratch_is_valid(svm))
3346 goto vmgexit_err;
3347 } else {
3348 if (!(control->exit_info_1 & SVM_IOIO_TYPE_MASK))
3349 if (!kvm_ghcb_rax_is_valid(svm))
3350 goto vmgexit_err;
3351 }
3352 break;
3353 case SVM_EXIT_MSR:
3354 if (!kvm_ghcb_rcx_is_valid(svm))
3355 goto vmgexit_err;
3356 if (control->exit_info_1) {
3357 if (!kvm_ghcb_rax_is_valid(svm) ||
3358 !kvm_ghcb_rdx_is_valid(svm))
3359 goto vmgexit_err;
3360 }
3361 break;
3362 case SVM_EXIT_VMMCALL:
3363 if (!kvm_ghcb_rax_is_valid(svm) ||
3364 !kvm_ghcb_cpl_is_valid(svm))
3365 goto vmgexit_err;
3366 break;
3367 case SVM_EXIT_RDTSCP:
3368 break;
3369 case SVM_EXIT_WBINVD:
3370 break;
3371 case SVM_EXIT_MONITOR:
3372 if (!kvm_ghcb_rax_is_valid(svm) ||
3373 !kvm_ghcb_rcx_is_valid(svm) ||
3374 !kvm_ghcb_rdx_is_valid(svm))
3375 goto vmgexit_err;
3376 break;
3377 case SVM_EXIT_MWAIT:
3378 if (!kvm_ghcb_rax_is_valid(svm) ||
3379 !kvm_ghcb_rcx_is_valid(svm))
3380 goto vmgexit_err;
3381 break;
3382 case SVM_VMGEXIT_MMIO_READ:
3383 case SVM_VMGEXIT_MMIO_WRITE:
3384 if (!kvm_ghcb_sw_scratch_is_valid(svm))
3385 goto vmgexit_err;
3386 break;
3387 case SVM_VMGEXIT_AP_CREATION:
3388 if (!sev_snp_guest(vcpu->kvm))
3389 goto vmgexit_err;
3390 if (lower_32_bits(control->exit_info_1) != SVM_VMGEXIT_AP_DESTROY)
3391 if (!kvm_ghcb_rax_is_valid(svm))
3392 goto vmgexit_err;
3393 break;
3394 case SVM_VMGEXIT_NMI_COMPLETE:
3395 case SVM_VMGEXIT_AP_HLT_LOOP:
3396 case SVM_VMGEXIT_AP_JUMP_TABLE:
3397 case SVM_VMGEXIT_UNSUPPORTED_EVENT:
3398 case SVM_VMGEXIT_HV_FEATURES:
3399 case SVM_VMGEXIT_TERM_REQUEST:
3400 break;
3401 case SVM_VMGEXIT_PSC:
3402 if (!sev_snp_guest(vcpu->kvm) || !kvm_ghcb_sw_scratch_is_valid(svm))
3403 goto vmgexit_err;
3404 break;
3405 case SVM_VMGEXIT_GUEST_REQUEST:
3406 case SVM_VMGEXIT_EXT_GUEST_REQUEST:
3407 if (!sev_snp_guest(vcpu->kvm) ||
3408 !PAGE_ALIGNED(control->exit_info_1) ||
3409 !PAGE_ALIGNED(control->exit_info_2) ||
3410 control->exit_info_1 == control->exit_info_2)
3411 goto vmgexit_err;
3412 break;
3413 default:
3414 reason = GHCB_ERR_INVALID_EVENT;
3415 goto vmgexit_err;
3416 }
3417
3418 return 0;
3419
3420 vmgexit_err:
3421 if (reason == GHCB_ERR_INVALID_USAGE) {
3422 vcpu_unimpl(vcpu, "vmgexit: ghcb usage %#x is not valid\n",
3423 svm->sev_es.ghcb->ghcb_usage);
3424 } else if (reason == GHCB_ERR_INVALID_EVENT) {
3425 vcpu_unimpl(vcpu, "vmgexit: exit code %#llx is not valid\n",
3426 exit_code);
3427 } else {
3428 vcpu_unimpl(vcpu, "vmgexit: exit code %#llx input is not valid\n",
3429 exit_code);
3430 dump_ghcb(svm);
3431 }
3432
3433 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
3434 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, reason);
3435
3436 /* Resume the guest to "return" the error code. */
3437 return 1;
3438 }
3439
sev_es_unmap_ghcb(struct vcpu_svm * svm)3440 void sev_es_unmap_ghcb(struct vcpu_svm *svm)
3441 {
3442 /* Clear any indication that the vCPU is in a type of AP Reset Hold */
3443 svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NONE;
3444
3445 if (!svm->sev_es.ghcb)
3446 return;
3447
3448 if (svm->sev_es.ghcb_sa_free) {
3449 /*
3450 * The scratch area lives outside the GHCB, so there is a
3451 * buffer that, depending on the operation performed, may
3452 * need to be synced, then freed.
3453 */
3454 if (svm->sev_es.ghcb_sa_sync) {
3455 kvm_write_guest(svm->vcpu.kvm,
3456 svm->sev_es.sw_scratch,
3457 svm->sev_es.ghcb_sa,
3458 svm->sev_es.ghcb_sa_len);
3459 svm->sev_es.ghcb_sa_sync = false;
3460 }
3461
3462 kvfree(svm->sev_es.ghcb_sa);
3463 svm->sev_es.ghcb_sa = NULL;
3464 svm->sev_es.ghcb_sa_free = false;
3465 }
3466
3467 trace_kvm_vmgexit_exit(svm->vcpu.vcpu_id, svm->sev_es.ghcb);
3468
3469 sev_es_sync_to_ghcb(svm);
3470
3471 kvm_vcpu_unmap(&svm->vcpu, &svm->sev_es.ghcb_map);
3472 svm->sev_es.ghcb = NULL;
3473 }
3474
pre_sev_run(struct vcpu_svm * svm,int cpu)3475 void pre_sev_run(struct vcpu_svm *svm, int cpu)
3476 {
3477 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
3478 unsigned int asid = sev_get_asid(svm->vcpu.kvm);
3479
3480 /* Assign the asid allocated with this SEV guest */
3481 svm->asid = asid;
3482
3483 /*
3484 * Flush guest TLB:
3485 *
3486 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
3487 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
3488 */
3489 if (sd->sev_vmcbs[asid] == svm->vmcb &&
3490 svm->vcpu.arch.last_vmentry_cpu == cpu)
3491 return;
3492
3493 sd->sev_vmcbs[asid] = svm->vmcb;
3494 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3495 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3496 }
3497
3498 #define GHCB_SCRATCH_AREA_LIMIT (16ULL * PAGE_SIZE)
setup_vmgexit_scratch(struct vcpu_svm * svm,bool sync,u64 len)3499 static int setup_vmgexit_scratch(struct vcpu_svm *svm, bool sync, u64 len)
3500 {
3501 struct vmcb_control_area *control = &svm->vmcb->control;
3502 u64 ghcb_scratch_beg, ghcb_scratch_end;
3503 u64 scratch_gpa_beg, scratch_gpa_end;
3504 void *scratch_va;
3505
3506 scratch_gpa_beg = svm->sev_es.sw_scratch;
3507 if (!scratch_gpa_beg) {
3508 pr_err("vmgexit: scratch gpa not provided\n");
3509 goto e_scratch;
3510 }
3511
3512 scratch_gpa_end = scratch_gpa_beg + len;
3513 if (scratch_gpa_end < scratch_gpa_beg) {
3514 pr_err("vmgexit: scratch length (%#llx) not valid for scratch address (%#llx)\n",
3515 len, scratch_gpa_beg);
3516 goto e_scratch;
3517 }
3518
3519 if ((scratch_gpa_beg & PAGE_MASK) == control->ghcb_gpa) {
3520 /* Scratch area begins within GHCB */
3521 ghcb_scratch_beg = control->ghcb_gpa +
3522 offsetof(struct ghcb, shared_buffer);
3523 ghcb_scratch_end = control->ghcb_gpa +
3524 offsetof(struct ghcb, reserved_0xff0);
3525
3526 /*
3527 * If the scratch area begins within the GHCB, it must be
3528 * completely contained in the GHCB shared buffer area.
3529 */
3530 if (scratch_gpa_beg < ghcb_scratch_beg ||
3531 scratch_gpa_end > ghcb_scratch_end) {
3532 pr_err("vmgexit: scratch area is outside of GHCB shared buffer area (%#llx - %#llx)\n",
3533 scratch_gpa_beg, scratch_gpa_end);
3534 goto e_scratch;
3535 }
3536
3537 scratch_va = (void *)svm->sev_es.ghcb;
3538 scratch_va += (scratch_gpa_beg - control->ghcb_gpa);
3539 } else {
3540 /*
3541 * The guest memory must be read into a kernel buffer, so
3542 * limit the size
3543 */
3544 if (len > GHCB_SCRATCH_AREA_LIMIT) {
3545 pr_err("vmgexit: scratch area exceeds KVM limits (%#llx requested, %#llx limit)\n",
3546 len, GHCB_SCRATCH_AREA_LIMIT);
3547 goto e_scratch;
3548 }
3549 scratch_va = kvzalloc(len, GFP_KERNEL_ACCOUNT);
3550 if (!scratch_va)
3551 return -ENOMEM;
3552
3553 if (kvm_read_guest(svm->vcpu.kvm, scratch_gpa_beg, scratch_va, len)) {
3554 /* Unable to copy scratch area from guest */
3555 pr_err("vmgexit: kvm_read_guest for scratch area failed\n");
3556
3557 kvfree(scratch_va);
3558 return -EFAULT;
3559 }
3560
3561 /*
3562 * The scratch area is outside the GHCB. The operation will
3563 * dictate whether the buffer needs to be synced before running
3564 * the vCPU next time (i.e. a read was requested so the data
3565 * must be written back to the guest memory).
3566 */
3567 svm->sev_es.ghcb_sa_sync = sync;
3568 svm->sev_es.ghcb_sa_free = true;
3569 }
3570
3571 svm->sev_es.ghcb_sa = scratch_va;
3572 svm->sev_es.ghcb_sa_len = len;
3573
3574 return 0;
3575
3576 e_scratch:
3577 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
3578 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_SCRATCH_AREA);
3579
3580 return 1;
3581 }
3582
set_ghcb_msr_bits(struct vcpu_svm * svm,u64 value,u64 mask,unsigned int pos)3583 static void set_ghcb_msr_bits(struct vcpu_svm *svm, u64 value, u64 mask,
3584 unsigned int pos)
3585 {
3586 svm->vmcb->control.ghcb_gpa &= ~(mask << pos);
3587 svm->vmcb->control.ghcb_gpa |= (value & mask) << pos;
3588 }
3589
get_ghcb_msr_bits(struct vcpu_svm * svm,u64 mask,unsigned int pos)3590 static u64 get_ghcb_msr_bits(struct vcpu_svm *svm, u64 mask, unsigned int pos)
3591 {
3592 return (svm->vmcb->control.ghcb_gpa >> pos) & mask;
3593 }
3594
set_ghcb_msr(struct vcpu_svm * svm,u64 value)3595 static void set_ghcb_msr(struct vcpu_svm *svm, u64 value)
3596 {
3597 svm->vmcb->control.ghcb_gpa = value;
3598 }
3599
snp_rmptable_psmash(kvm_pfn_t pfn)3600 static int snp_rmptable_psmash(kvm_pfn_t pfn)
3601 {
3602 int ret;
3603
3604 pfn = pfn & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
3605
3606 /*
3607 * PSMASH_FAIL_INUSE indicates another processor is modifying the
3608 * entry, so retry until that's no longer the case.
3609 */
3610 do {
3611 ret = psmash(pfn);
3612 } while (ret == PSMASH_FAIL_INUSE);
3613
3614 return ret;
3615 }
3616
snp_complete_psc_msr(struct kvm_vcpu * vcpu)3617 static int snp_complete_psc_msr(struct kvm_vcpu *vcpu)
3618 {
3619 struct vcpu_svm *svm = to_svm(vcpu);
3620
3621 if (vcpu->run->hypercall.ret)
3622 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3623 else
3624 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP);
3625
3626 return 1; /* resume guest */
3627 }
3628
snp_begin_psc_msr(struct vcpu_svm * svm,u64 ghcb_msr)3629 static int snp_begin_psc_msr(struct vcpu_svm *svm, u64 ghcb_msr)
3630 {
3631 u64 gpa = gfn_to_gpa(GHCB_MSR_PSC_REQ_TO_GFN(ghcb_msr));
3632 u8 op = GHCB_MSR_PSC_REQ_TO_OP(ghcb_msr);
3633 struct kvm_vcpu *vcpu = &svm->vcpu;
3634
3635 if (op != SNP_PAGE_STATE_PRIVATE && op != SNP_PAGE_STATE_SHARED) {
3636 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3637 return 1; /* resume guest */
3638 }
3639
3640 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) {
3641 set_ghcb_msr(svm, GHCB_MSR_PSC_RESP_ERROR);
3642 return 1; /* resume guest */
3643 }
3644
3645 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
3646 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
3647 /*
3648 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
3649 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
3650 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
3651 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
3652 */
3653 vcpu->run->hypercall.ret = 0;
3654 vcpu->run->hypercall.args[0] = gpa;
3655 vcpu->run->hypercall.args[1] = 1;
3656 vcpu->run->hypercall.args[2] = (op == SNP_PAGE_STATE_PRIVATE)
3657 ? KVM_MAP_GPA_RANGE_ENCRYPTED
3658 : KVM_MAP_GPA_RANGE_DECRYPTED;
3659 vcpu->run->hypercall.args[2] |= KVM_MAP_GPA_RANGE_PAGE_SZ_4K;
3660
3661 vcpu->arch.complete_userspace_io = snp_complete_psc_msr;
3662
3663 return 0; /* forward request to userspace */
3664 }
3665
3666 struct psc_buffer {
3667 struct psc_hdr hdr;
3668 struct psc_entry entries[];
3669 } __packed;
3670
3671 static int snp_begin_psc(struct vcpu_svm *svm, struct psc_buffer *psc);
3672
snp_complete_psc(struct vcpu_svm * svm,u64 psc_ret)3673 static void snp_complete_psc(struct vcpu_svm *svm, u64 psc_ret)
3674 {
3675 svm->sev_es.psc_inflight = 0;
3676 svm->sev_es.psc_idx = 0;
3677 svm->sev_es.psc_2m = false;
3678 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, psc_ret);
3679 }
3680
__snp_complete_one_psc(struct vcpu_svm * svm)3681 static void __snp_complete_one_psc(struct vcpu_svm *svm)
3682 {
3683 struct psc_buffer *psc = svm->sev_es.ghcb_sa;
3684 struct psc_entry *entries = psc->entries;
3685 struct psc_hdr *hdr = &psc->hdr;
3686 __u16 idx;
3687
3688 /*
3689 * Everything in-flight has been processed successfully. Update the
3690 * corresponding entries in the guest's PSC buffer and zero out the
3691 * count of in-flight PSC entries.
3692 */
3693 for (idx = svm->sev_es.psc_idx; svm->sev_es.psc_inflight;
3694 svm->sev_es.psc_inflight--, idx++) {
3695 struct psc_entry *entry = &entries[idx];
3696
3697 entry->cur_page = entry->pagesize ? 512 : 1;
3698 }
3699
3700 hdr->cur_entry = idx;
3701 }
3702
snp_complete_one_psc(struct kvm_vcpu * vcpu)3703 static int snp_complete_one_psc(struct kvm_vcpu *vcpu)
3704 {
3705 struct vcpu_svm *svm = to_svm(vcpu);
3706 struct psc_buffer *psc = svm->sev_es.ghcb_sa;
3707
3708 if (vcpu->run->hypercall.ret) {
3709 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3710 return 1; /* resume guest */
3711 }
3712
3713 __snp_complete_one_psc(svm);
3714
3715 /* Handle the next range (if any). */
3716 return snp_begin_psc(svm, psc);
3717 }
3718
snp_begin_psc(struct vcpu_svm * svm,struct psc_buffer * psc)3719 static int snp_begin_psc(struct vcpu_svm *svm, struct psc_buffer *psc)
3720 {
3721 struct psc_entry *entries = psc->entries;
3722 struct kvm_vcpu *vcpu = &svm->vcpu;
3723 struct psc_hdr *hdr = &psc->hdr;
3724 struct psc_entry entry_start;
3725 u16 idx, idx_start, idx_end;
3726 int npages;
3727 bool huge;
3728 u64 gfn;
3729
3730 if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) {
3731 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3732 return 1;
3733 }
3734
3735 next_range:
3736 /* There should be no other PSCs in-flight at this point. */
3737 if (WARN_ON_ONCE(svm->sev_es.psc_inflight)) {
3738 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_GENERIC);
3739 return 1;
3740 }
3741
3742 /*
3743 * The PSC descriptor buffer can be modified by a misbehaved guest after
3744 * validation, so take care to only use validated copies of values used
3745 * for things like array indexing.
3746 */
3747 idx_start = hdr->cur_entry;
3748 idx_end = hdr->end_entry;
3749
3750 if (idx_end >= VMGEXIT_PSC_MAX_COUNT) {
3751 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_HDR);
3752 return 1;
3753 }
3754
3755 /* Find the start of the next range which needs processing. */
3756 for (idx = idx_start; idx <= idx_end; idx++, hdr->cur_entry++) {
3757 entry_start = entries[idx];
3758
3759 gfn = entry_start.gfn;
3760 huge = entry_start.pagesize;
3761 npages = huge ? 512 : 1;
3762
3763 if (entry_start.cur_page > npages || !IS_ALIGNED(gfn, npages)) {
3764 snp_complete_psc(svm, VMGEXIT_PSC_ERROR_INVALID_ENTRY);
3765 return 1;
3766 }
3767
3768 if (entry_start.cur_page) {
3769 /*
3770 * If this is a partially-completed 2M range, force 4K handling
3771 * for the remaining pages since they're effectively split at
3772 * this point. Subsequent code should ensure this doesn't get
3773 * combined with adjacent PSC entries where 2M handling is still
3774 * possible.
3775 */
3776 npages -= entry_start.cur_page;
3777 gfn += entry_start.cur_page;
3778 huge = false;
3779 }
3780
3781 if (npages)
3782 break;
3783 }
3784
3785 if (idx > idx_end) {
3786 /* Nothing more to process. */
3787 snp_complete_psc(svm, 0);
3788 return 1;
3789 }
3790
3791 svm->sev_es.psc_2m = huge;
3792 svm->sev_es.psc_idx = idx;
3793 svm->sev_es.psc_inflight = 1;
3794
3795 /*
3796 * Find all subsequent PSC entries that contain adjacent GPA
3797 * ranges/operations and can be combined into a single
3798 * KVM_HC_MAP_GPA_RANGE exit.
3799 */
3800 while (++idx <= idx_end) {
3801 struct psc_entry entry = entries[idx];
3802
3803 if (entry.operation != entry_start.operation ||
3804 entry.gfn != entry_start.gfn + npages ||
3805 entry.cur_page || !!entry.pagesize != huge)
3806 break;
3807
3808 svm->sev_es.psc_inflight++;
3809 npages += huge ? 512 : 1;
3810 }
3811
3812 switch (entry_start.operation) {
3813 case VMGEXIT_PSC_OP_PRIVATE:
3814 case VMGEXIT_PSC_OP_SHARED:
3815 vcpu->run->exit_reason = KVM_EXIT_HYPERCALL;
3816 vcpu->run->hypercall.nr = KVM_HC_MAP_GPA_RANGE;
3817 /*
3818 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
3819 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
3820 * it was always zero on KVM_EXIT_HYPERCALL. Since KVM is now overwriting
3821 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
3822 */
3823 vcpu->run->hypercall.ret = 0;
3824 vcpu->run->hypercall.args[0] = gfn_to_gpa(gfn);
3825 vcpu->run->hypercall.args[1] = npages;
3826 vcpu->run->hypercall.args[2] = entry_start.operation == VMGEXIT_PSC_OP_PRIVATE
3827 ? KVM_MAP_GPA_RANGE_ENCRYPTED
3828 : KVM_MAP_GPA_RANGE_DECRYPTED;
3829 vcpu->run->hypercall.args[2] |= entry_start.pagesize
3830 ? KVM_MAP_GPA_RANGE_PAGE_SZ_2M
3831 : KVM_MAP_GPA_RANGE_PAGE_SZ_4K;
3832 vcpu->arch.complete_userspace_io = snp_complete_one_psc;
3833 return 0; /* forward request to userspace */
3834 default:
3835 /*
3836 * Only shared/private PSC operations are currently supported, so if the
3837 * entire range consists of unsupported operations (e.g. SMASH/UNSMASH),
3838 * then consider the entire range completed and avoid exiting to
3839 * userspace. In theory snp_complete_psc() can always be called directly
3840 * at this point to complete the current range and start the next one,
3841 * but that could lead to unexpected levels of recursion.
3842 */
3843 __snp_complete_one_psc(svm);
3844 goto next_range;
3845 }
3846
3847 BUG();
3848 }
3849
__sev_snp_update_protected_guest_state(struct kvm_vcpu * vcpu)3850 static int __sev_snp_update_protected_guest_state(struct kvm_vcpu *vcpu)
3851 {
3852 struct vcpu_svm *svm = to_svm(vcpu);
3853
3854 WARN_ON(!mutex_is_locked(&svm->sev_es.snp_vmsa_mutex));
3855
3856 /* Mark the vCPU as offline and not runnable */
3857 vcpu->arch.pv.pv_unhalted = false;
3858 vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
3859
3860 /* Clear use of the VMSA */
3861 svm->vmcb->control.vmsa_pa = INVALID_PAGE;
3862
3863 if (VALID_PAGE(svm->sev_es.snp_vmsa_gpa)) {
3864 gfn_t gfn = gpa_to_gfn(svm->sev_es.snp_vmsa_gpa);
3865 struct kvm_memory_slot *slot;
3866 struct page *page;
3867 kvm_pfn_t pfn;
3868
3869 slot = gfn_to_memslot(vcpu->kvm, gfn);
3870 if (!slot)
3871 return -EINVAL;
3872
3873 /*
3874 * The new VMSA will be private memory guest memory, so
3875 * retrieve the PFN from the gmem backend.
3876 */
3877 if (kvm_gmem_get_pfn(vcpu->kvm, slot, gfn, &pfn, &page, NULL))
3878 return -EINVAL;
3879
3880 /*
3881 * From this point forward, the VMSA will always be a
3882 * guest-mapped page rather than the initial one allocated
3883 * by KVM in svm->sev_es.vmsa. In theory, svm->sev_es.vmsa
3884 * could be free'd and cleaned up here, but that involves
3885 * cleanups like wbinvd_on_all_cpus() which would ideally
3886 * be handled during teardown rather than guest boot.
3887 * Deferring that also allows the existing logic for SEV-ES
3888 * VMSAs to be re-used with minimal SNP-specific changes.
3889 */
3890 svm->sev_es.snp_has_guest_vmsa = true;
3891
3892 /* Use the new VMSA */
3893 svm->vmcb->control.vmsa_pa = pfn_to_hpa(pfn);
3894
3895 /* Mark the vCPU as runnable */
3896 vcpu->arch.pv.pv_unhalted = false;
3897 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3898
3899 svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
3900
3901 /*
3902 * gmem pages aren't currently migratable, but if this ever
3903 * changes then care should be taken to ensure
3904 * svm->sev_es.vmsa is pinned through some other means.
3905 */
3906 kvm_release_page_clean(page);
3907 }
3908
3909 /*
3910 * When replacing the VMSA during SEV-SNP AP creation,
3911 * mark the VMCB dirty so that full state is always reloaded.
3912 */
3913 vmcb_mark_all_dirty(svm->vmcb);
3914
3915 return 0;
3916 }
3917
3918 /*
3919 * Invoked as part of svm_vcpu_reset() processing of an init event.
3920 */
sev_snp_init_protected_guest_state(struct kvm_vcpu * vcpu)3921 void sev_snp_init_protected_guest_state(struct kvm_vcpu *vcpu)
3922 {
3923 struct vcpu_svm *svm = to_svm(vcpu);
3924 int ret;
3925
3926 if (!sev_snp_guest(vcpu->kvm))
3927 return;
3928
3929 mutex_lock(&svm->sev_es.snp_vmsa_mutex);
3930
3931 if (!svm->sev_es.snp_ap_waiting_for_reset)
3932 goto unlock;
3933
3934 svm->sev_es.snp_ap_waiting_for_reset = false;
3935
3936 ret = __sev_snp_update_protected_guest_state(vcpu);
3937 if (ret)
3938 vcpu_unimpl(vcpu, "snp: AP state update on init failed\n");
3939
3940 unlock:
3941 mutex_unlock(&svm->sev_es.snp_vmsa_mutex);
3942 }
3943
sev_snp_ap_creation(struct vcpu_svm * svm)3944 static int sev_snp_ap_creation(struct vcpu_svm *svm)
3945 {
3946 struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
3947 struct kvm_vcpu *vcpu = &svm->vcpu;
3948 struct kvm_vcpu *target_vcpu;
3949 struct vcpu_svm *target_svm;
3950 unsigned int request;
3951 unsigned int apic_id;
3952 bool kick;
3953 int ret;
3954
3955 request = lower_32_bits(svm->vmcb->control.exit_info_1);
3956 apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
3957
3958 /* Validate the APIC ID */
3959 target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);
3960 if (!target_vcpu) {
3961 vcpu_unimpl(vcpu, "vmgexit: invalid AP APIC ID [%#x] from guest\n",
3962 apic_id);
3963 return -EINVAL;
3964 }
3965
3966 ret = 0;
3967
3968 target_svm = to_svm(target_vcpu);
3969
3970 /*
3971 * The target vCPU is valid, so the vCPU will be kicked unless the
3972 * request is for CREATE_ON_INIT.
3973 */
3974 kick = true;
3975
3976 mutex_lock(&target_svm->sev_es.snp_vmsa_mutex);
3977
3978 /* Interrupt injection mode shouldn't change for AP creation */
3979 if (request < SVM_VMGEXIT_AP_DESTROY) {
3980 u64 sev_features;
3981
3982 sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
3983 sev_features ^= sev->vmsa_features;
3984
3985 if (sev_features & SVM_SEV_FEAT_INT_INJ_MODES) {
3986 vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
3987 vcpu->arch.regs[VCPU_REGS_RAX]);
3988 ret = -EINVAL;
3989 goto out;
3990 }
3991 }
3992
3993 switch (request) {
3994 case SVM_VMGEXIT_AP_CREATE_ON_INIT:
3995 kick = false;
3996 fallthrough;
3997 case SVM_VMGEXIT_AP_CREATE:
3998 if (!page_address_valid(vcpu, svm->vmcb->control.exit_info_2)) {
3999 vcpu_unimpl(vcpu, "vmgexit: invalid AP VMSA address [%#llx] from guest\n",
4000 svm->vmcb->control.exit_info_2);
4001 ret = -EINVAL;
4002 goto out;
4003 }
4004
4005 /*
4006 * Malicious guest can RMPADJUST a large page into VMSA which
4007 * will hit the SNP erratum where the CPU will incorrectly signal
4008 * an RMP violation #PF if a hugepage collides with the RMP entry
4009 * of VMSA page, reject the AP CREATE request if VMSA address from
4010 * guest is 2M aligned.
4011 */
4012 if (IS_ALIGNED(svm->vmcb->control.exit_info_2, PMD_SIZE)) {
4013 vcpu_unimpl(vcpu,
4014 "vmgexit: AP VMSA address [%llx] from guest is unsafe as it is 2M aligned\n",
4015 svm->vmcb->control.exit_info_2);
4016 ret = -EINVAL;
4017 goto out;
4018 }
4019
4020 target_svm->sev_es.snp_vmsa_gpa = svm->vmcb->control.exit_info_2;
4021 break;
4022 case SVM_VMGEXIT_AP_DESTROY:
4023 target_svm->sev_es.snp_vmsa_gpa = INVALID_PAGE;
4024 break;
4025 default:
4026 vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
4027 request);
4028 ret = -EINVAL;
4029 goto out;
4030 }
4031
4032 target_svm->sev_es.snp_ap_waiting_for_reset = true;
4033
4034 if (kick) {
4035 kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
4036 kvm_vcpu_kick(target_vcpu);
4037 }
4038
4039 out:
4040 mutex_unlock(&target_svm->sev_es.snp_vmsa_mutex);
4041
4042 return ret;
4043 }
4044
snp_handle_guest_req(struct vcpu_svm * svm,gpa_t req_gpa,gpa_t resp_gpa)4045 static int snp_handle_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
4046 {
4047 struct sev_data_snp_guest_request data = {0};
4048 struct kvm *kvm = svm->vcpu.kvm;
4049 struct kvm_sev_info *sev = to_kvm_sev_info(kvm);
4050 sev_ret_code fw_err = 0;
4051 int ret;
4052
4053 if (!sev_snp_guest(kvm))
4054 return -EINVAL;
4055
4056 mutex_lock(&sev->guest_req_mutex);
4057
4058 if (kvm_read_guest(kvm, req_gpa, sev->guest_req_buf, PAGE_SIZE)) {
4059 ret = -EIO;
4060 goto out_unlock;
4061 }
4062
4063 data.gctx_paddr = __psp_pa(sev->snp_context);
4064 data.req_paddr = __psp_pa(sev->guest_req_buf);
4065 data.res_paddr = __psp_pa(sev->guest_resp_buf);
4066
4067 /*
4068 * Firmware failures are propagated on to guest, but any other failure
4069 * condition along the way should be reported to userspace. E.g. if
4070 * the PSP is dead and commands are timing out.
4071 */
4072 ret = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &fw_err);
4073 if (ret && !fw_err)
4074 goto out_unlock;
4075
4076 if (kvm_write_guest(kvm, resp_gpa, sev->guest_resp_buf, PAGE_SIZE)) {
4077 ret = -EIO;
4078 goto out_unlock;
4079 }
4080
4081 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, SNP_GUEST_ERR(0, fw_err));
4082
4083 ret = 1; /* resume guest */
4084
4085 out_unlock:
4086 mutex_unlock(&sev->guest_req_mutex);
4087 return ret;
4088 }
4089
snp_handle_ext_guest_req(struct vcpu_svm * svm,gpa_t req_gpa,gpa_t resp_gpa)4090 static int snp_handle_ext_guest_req(struct vcpu_svm *svm, gpa_t req_gpa, gpa_t resp_gpa)
4091 {
4092 struct kvm *kvm = svm->vcpu.kvm;
4093 u8 msg_type;
4094
4095 if (!sev_snp_guest(kvm))
4096 return -EINVAL;
4097
4098 if (kvm_read_guest(kvm, req_gpa + offsetof(struct snp_guest_msg_hdr, msg_type),
4099 &msg_type, 1))
4100 return -EIO;
4101
4102 /*
4103 * As per GHCB spec, requests of type MSG_REPORT_REQ also allow for
4104 * additional certificate data to be provided alongside the attestation
4105 * report via the guest-provided data pages indicated by RAX/RBX. The
4106 * certificate data is optional and requires additional KVM enablement
4107 * to provide an interface for userspace to provide it, but KVM still
4108 * needs to be able to handle extended guest requests either way. So
4109 * provide a stub implementation that will always return an empty
4110 * certificate table in the guest-provided data pages.
4111 */
4112 if (msg_type == SNP_MSG_REPORT_REQ) {
4113 struct kvm_vcpu *vcpu = &svm->vcpu;
4114 u64 data_npages;
4115 gpa_t data_gpa;
4116
4117 if (!kvm_ghcb_rax_is_valid(svm) || !kvm_ghcb_rbx_is_valid(svm))
4118 goto request_invalid;
4119
4120 data_gpa = vcpu->arch.regs[VCPU_REGS_RAX];
4121 data_npages = vcpu->arch.regs[VCPU_REGS_RBX];
4122
4123 if (!PAGE_ALIGNED(data_gpa))
4124 goto request_invalid;
4125
4126 /*
4127 * As per GHCB spec (see "SNP Extended Guest Request"), the
4128 * certificate table is terminated by 24-bytes of zeroes.
4129 */
4130 if (data_npages && kvm_clear_guest(kvm, data_gpa, 24))
4131 return -EIO;
4132 }
4133
4134 return snp_handle_guest_req(svm, req_gpa, resp_gpa);
4135
4136 request_invalid:
4137 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
4138 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_INPUT);
4139 return 1; /* resume guest */
4140 }
4141
sev_handle_vmgexit_msr_protocol(struct vcpu_svm * svm)4142 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
4143 {
4144 struct vmcb_control_area *control = &svm->vmcb->control;
4145 struct kvm_vcpu *vcpu = &svm->vcpu;
4146 struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
4147 u64 ghcb_info;
4148 int ret = 1;
4149
4150 ghcb_info = control->ghcb_gpa & GHCB_MSR_INFO_MASK;
4151
4152 trace_kvm_vmgexit_msr_protocol_enter(svm->vcpu.vcpu_id,
4153 control->ghcb_gpa);
4154
4155 switch (ghcb_info) {
4156 case GHCB_MSR_SEV_INFO_REQ:
4157 set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version,
4158 GHCB_VERSION_MIN,
4159 sev_enc_bit));
4160 break;
4161 case GHCB_MSR_CPUID_REQ: {
4162 u64 cpuid_fn, cpuid_reg, cpuid_value;
4163
4164 cpuid_fn = get_ghcb_msr_bits(svm,
4165 GHCB_MSR_CPUID_FUNC_MASK,
4166 GHCB_MSR_CPUID_FUNC_POS);
4167
4168 /* Initialize the registers needed by the CPUID intercept */
4169 vcpu->arch.regs[VCPU_REGS_RAX] = cpuid_fn;
4170 vcpu->arch.regs[VCPU_REGS_RCX] = 0;
4171
4172 ret = svm_invoke_exit_handler(vcpu, SVM_EXIT_CPUID);
4173 if (!ret) {
4174 /* Error, keep GHCB MSR value as-is */
4175 break;
4176 }
4177
4178 cpuid_reg = get_ghcb_msr_bits(svm,
4179 GHCB_MSR_CPUID_REG_MASK,
4180 GHCB_MSR_CPUID_REG_POS);
4181 if (cpuid_reg == 0)
4182 cpuid_value = vcpu->arch.regs[VCPU_REGS_RAX];
4183 else if (cpuid_reg == 1)
4184 cpuid_value = vcpu->arch.regs[VCPU_REGS_RBX];
4185 else if (cpuid_reg == 2)
4186 cpuid_value = vcpu->arch.regs[VCPU_REGS_RCX];
4187 else
4188 cpuid_value = vcpu->arch.regs[VCPU_REGS_RDX];
4189
4190 set_ghcb_msr_bits(svm, cpuid_value,
4191 GHCB_MSR_CPUID_VALUE_MASK,
4192 GHCB_MSR_CPUID_VALUE_POS);
4193
4194 set_ghcb_msr_bits(svm, GHCB_MSR_CPUID_RESP,
4195 GHCB_MSR_INFO_MASK,
4196 GHCB_MSR_INFO_POS);
4197 break;
4198 }
4199 case GHCB_MSR_AP_RESET_HOLD_REQ:
4200 svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_MSR_PROTO;
4201 ret = kvm_emulate_ap_reset_hold(&svm->vcpu);
4202
4203 /*
4204 * Preset the result to a non-SIPI return and then only set
4205 * the result to non-zero when delivering a SIPI.
4206 */
4207 set_ghcb_msr_bits(svm, 0,
4208 GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,
4209 GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
4210
4211 set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP,
4212 GHCB_MSR_INFO_MASK,
4213 GHCB_MSR_INFO_POS);
4214 break;
4215 case GHCB_MSR_HV_FT_REQ:
4216 set_ghcb_msr_bits(svm, GHCB_HV_FT_SUPPORTED,
4217 GHCB_MSR_HV_FT_MASK, GHCB_MSR_HV_FT_POS);
4218 set_ghcb_msr_bits(svm, GHCB_MSR_HV_FT_RESP,
4219 GHCB_MSR_INFO_MASK, GHCB_MSR_INFO_POS);
4220 break;
4221 case GHCB_MSR_PREF_GPA_REQ:
4222 if (!sev_snp_guest(vcpu->kvm))
4223 goto out_terminate;
4224
4225 set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_NONE, GHCB_MSR_GPA_VALUE_MASK,
4226 GHCB_MSR_GPA_VALUE_POS);
4227 set_ghcb_msr_bits(svm, GHCB_MSR_PREF_GPA_RESP, GHCB_MSR_INFO_MASK,
4228 GHCB_MSR_INFO_POS);
4229 break;
4230 case GHCB_MSR_REG_GPA_REQ: {
4231 u64 gfn;
4232
4233 if (!sev_snp_guest(vcpu->kvm))
4234 goto out_terminate;
4235
4236 gfn = get_ghcb_msr_bits(svm, GHCB_MSR_GPA_VALUE_MASK,
4237 GHCB_MSR_GPA_VALUE_POS);
4238
4239 svm->sev_es.ghcb_registered_gpa = gfn_to_gpa(gfn);
4240
4241 set_ghcb_msr_bits(svm, gfn, GHCB_MSR_GPA_VALUE_MASK,
4242 GHCB_MSR_GPA_VALUE_POS);
4243 set_ghcb_msr_bits(svm, GHCB_MSR_REG_GPA_RESP, GHCB_MSR_INFO_MASK,
4244 GHCB_MSR_INFO_POS);
4245 break;
4246 }
4247 case GHCB_MSR_PSC_REQ:
4248 if (!sev_snp_guest(vcpu->kvm))
4249 goto out_terminate;
4250
4251 ret = snp_begin_psc_msr(svm, control->ghcb_gpa);
4252 break;
4253 case GHCB_MSR_TERM_REQ: {
4254 u64 reason_set, reason_code;
4255
4256 reason_set = get_ghcb_msr_bits(svm,
4257 GHCB_MSR_TERM_REASON_SET_MASK,
4258 GHCB_MSR_TERM_REASON_SET_POS);
4259 reason_code = get_ghcb_msr_bits(svm,
4260 GHCB_MSR_TERM_REASON_MASK,
4261 GHCB_MSR_TERM_REASON_POS);
4262 pr_info("SEV-ES guest requested termination: %#llx:%#llx\n",
4263 reason_set, reason_code);
4264
4265 goto out_terminate;
4266 }
4267 default:
4268 /* Error, keep GHCB MSR value as-is */
4269 break;
4270 }
4271
4272 trace_kvm_vmgexit_msr_protocol_exit(svm->vcpu.vcpu_id,
4273 control->ghcb_gpa, ret);
4274
4275 return ret;
4276
4277 out_terminate:
4278 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
4279 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
4280 vcpu->run->system_event.ndata = 1;
4281 vcpu->run->system_event.data[0] = control->ghcb_gpa;
4282
4283 return 0;
4284 }
4285
sev_handle_vmgexit(struct kvm_vcpu * vcpu)4286 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
4287 {
4288 struct vcpu_svm *svm = to_svm(vcpu);
4289 struct vmcb_control_area *control = &svm->vmcb->control;
4290 u64 ghcb_gpa, exit_code;
4291 int ret;
4292
4293 /* Validate the GHCB */
4294 ghcb_gpa = control->ghcb_gpa;
4295 if (ghcb_gpa & GHCB_MSR_INFO_MASK)
4296 return sev_handle_vmgexit_msr_protocol(svm);
4297
4298 if (!ghcb_gpa) {
4299 vcpu_unimpl(vcpu, "vmgexit: GHCB gpa is not set\n");
4300
4301 /* Without a GHCB, just return right back to the guest */
4302 return 1;
4303 }
4304
4305 if (kvm_vcpu_map(vcpu, ghcb_gpa >> PAGE_SHIFT, &svm->sev_es.ghcb_map)) {
4306 /* Unable to map GHCB from guest */
4307 vcpu_unimpl(vcpu, "vmgexit: error mapping GHCB [%#llx] from guest\n",
4308 ghcb_gpa);
4309
4310 /* Without a GHCB, just return right back to the guest */
4311 return 1;
4312 }
4313
4314 svm->sev_es.ghcb = svm->sev_es.ghcb_map.hva;
4315
4316 trace_kvm_vmgexit_enter(vcpu->vcpu_id, svm->sev_es.ghcb);
4317
4318 sev_es_sync_from_ghcb(svm);
4319
4320 /* SEV-SNP guest requires that the GHCB GPA must be registered */
4321 if (sev_snp_guest(svm->vcpu.kvm) && !ghcb_gpa_is_registered(svm, ghcb_gpa)) {
4322 vcpu_unimpl(&svm->vcpu, "vmgexit: GHCB GPA [%#llx] is not registered.\n", ghcb_gpa);
4323 return -EINVAL;
4324 }
4325
4326 ret = sev_es_validate_vmgexit(svm);
4327 if (ret)
4328 return ret;
4329
4330 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 0);
4331 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 0);
4332
4333 exit_code = kvm_ghcb_get_sw_exit_code(control);
4334 switch (exit_code) {
4335 case SVM_VMGEXIT_MMIO_READ:
4336 ret = setup_vmgexit_scratch(svm, true, control->exit_info_2);
4337 if (ret)
4338 break;
4339
4340 ret = kvm_sev_es_mmio_read(vcpu,
4341 control->exit_info_1,
4342 control->exit_info_2,
4343 svm->sev_es.ghcb_sa);
4344 break;
4345 case SVM_VMGEXIT_MMIO_WRITE:
4346 ret = setup_vmgexit_scratch(svm, false, control->exit_info_2);
4347 if (ret)
4348 break;
4349
4350 ret = kvm_sev_es_mmio_write(vcpu,
4351 control->exit_info_1,
4352 control->exit_info_2,
4353 svm->sev_es.ghcb_sa);
4354 break;
4355 case SVM_VMGEXIT_NMI_COMPLETE:
4356 ++vcpu->stat.nmi_window_exits;
4357 svm->nmi_masked = false;
4358 kvm_make_request(KVM_REQ_EVENT, vcpu);
4359 ret = 1;
4360 break;
4361 case SVM_VMGEXIT_AP_HLT_LOOP:
4362 svm->sev_es.ap_reset_hold_type = AP_RESET_HOLD_NAE_EVENT;
4363 ret = kvm_emulate_ap_reset_hold(vcpu);
4364 break;
4365 case SVM_VMGEXIT_AP_JUMP_TABLE: {
4366 struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
4367
4368 switch (control->exit_info_1) {
4369 case 0:
4370 /* Set AP jump table address */
4371 sev->ap_jump_table = control->exit_info_2;
4372 break;
4373 case 1:
4374 /* Get AP jump table address */
4375 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, sev->ap_jump_table);
4376 break;
4377 default:
4378 pr_err("svm: vmgexit: unsupported AP jump table request - exit_info_1=%#llx\n",
4379 control->exit_info_1);
4380 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
4381 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_INPUT);
4382 }
4383
4384 ret = 1;
4385 break;
4386 }
4387 case SVM_VMGEXIT_HV_FEATURES:
4388 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_HV_FT_SUPPORTED);
4389
4390 ret = 1;
4391 break;
4392 case SVM_VMGEXIT_TERM_REQUEST:
4393 pr_info("SEV-ES guest requested termination: reason %#llx info %#llx\n",
4394 control->exit_info_1, control->exit_info_2);
4395 vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
4396 vcpu->run->system_event.type = KVM_SYSTEM_EVENT_SEV_TERM;
4397 vcpu->run->system_event.ndata = 1;
4398 vcpu->run->system_event.data[0] = control->ghcb_gpa;
4399 break;
4400 case SVM_VMGEXIT_PSC:
4401 ret = setup_vmgexit_scratch(svm, true, control->exit_info_2);
4402 if (ret)
4403 break;
4404
4405 ret = snp_begin_psc(svm, svm->sev_es.ghcb_sa);
4406 break;
4407 case SVM_VMGEXIT_AP_CREATION:
4408 ret = sev_snp_ap_creation(svm);
4409 if (ret) {
4410 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 2);
4411 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, GHCB_ERR_INVALID_INPUT);
4412 }
4413
4414 ret = 1;
4415 break;
4416 case SVM_VMGEXIT_GUEST_REQUEST:
4417 ret = snp_handle_guest_req(svm, control->exit_info_1, control->exit_info_2);
4418 break;
4419 case SVM_VMGEXIT_EXT_GUEST_REQUEST:
4420 ret = snp_handle_ext_guest_req(svm, control->exit_info_1, control->exit_info_2);
4421 break;
4422 case SVM_VMGEXIT_UNSUPPORTED_EVENT:
4423 vcpu_unimpl(vcpu,
4424 "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
4425 control->exit_info_1, control->exit_info_2);
4426 ret = -EINVAL;
4427 break;
4428 default:
4429 ret = svm_invoke_exit_handler(vcpu, exit_code);
4430 }
4431
4432 return ret;
4433 }
4434
sev_es_string_io(struct vcpu_svm * svm,int size,unsigned int port,int in)4435 int sev_es_string_io(struct vcpu_svm *svm, int size, unsigned int port, int in)
4436 {
4437 int count;
4438 int bytes;
4439 int r;
4440
4441 if (svm->vmcb->control.exit_info_2 > INT_MAX)
4442 return -EINVAL;
4443
4444 count = svm->vmcb->control.exit_info_2;
4445 if (unlikely(check_mul_overflow(count, size, &bytes)))
4446 return -EINVAL;
4447
4448 r = setup_vmgexit_scratch(svm, in, bytes);
4449 if (r)
4450 return r;
4451
4452 return kvm_sev_es_string_io(&svm->vcpu, size, port, svm->sev_es.ghcb_sa,
4453 count, in);
4454 }
4455
sev_es_vcpu_after_set_cpuid(struct vcpu_svm * svm)4456 static void sev_es_vcpu_after_set_cpuid(struct vcpu_svm *svm)
4457 {
4458 struct kvm_vcpu *vcpu = &svm->vcpu;
4459
4460 if (boot_cpu_has(X86_FEATURE_V_TSC_AUX)) {
4461 bool v_tsc_aux = guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) ||
4462 guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID);
4463
4464 set_msr_interception(vcpu, svm->msrpm, MSR_TSC_AUX, v_tsc_aux, v_tsc_aux);
4465 }
4466
4467 /*
4468 * For SEV-ES, accesses to MSR_IA32_XSS should not be intercepted if
4469 * the host/guest supports its use.
4470 *
4471 * KVM treats the guest as being capable of using XSAVES even if XSAVES
4472 * isn't enabled in guest CPUID as there is no intercept for XSAVES,
4473 * i.e. the guest can use XSAVES/XRSTOR to read/write XSS if XSAVE is
4474 * exposed to the guest and XSAVES is supported in hardware. Condition
4475 * full XSS passthrough on the guest being able to use XSAVES *and*
4476 * XSAVES being exposed to the guest so that KVM can at least honor
4477 * guest CPUID for RDMSR and WRMSR.
4478 */
4479 if (guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVES) &&
4480 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES))
4481 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 1, 1);
4482 else
4483 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_XSS, 0, 0);
4484 }
4485
sev_vcpu_after_set_cpuid(struct vcpu_svm * svm)4486 void sev_vcpu_after_set_cpuid(struct vcpu_svm *svm)
4487 {
4488 struct kvm_vcpu *vcpu = &svm->vcpu;
4489 struct kvm_cpuid_entry2 *best;
4490
4491 /* For sev guests, the memory encryption bit is not reserved in CR3. */
4492 best = kvm_find_cpuid_entry(vcpu, 0x8000001F);
4493 if (best)
4494 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4495
4496 if (sev_es_guest(svm->vcpu.kvm))
4497 sev_es_vcpu_after_set_cpuid(svm);
4498 }
4499
sev_es_init_vmcb(struct vcpu_svm * svm)4500 static void sev_es_init_vmcb(struct vcpu_svm *svm)
4501 {
4502 struct vmcb *vmcb = svm->vmcb01.ptr;
4503 struct kvm_vcpu *vcpu = &svm->vcpu;
4504
4505 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ES_ENABLE;
4506
4507 /*
4508 * An SEV-ES guest requires a VMSA area that is a separate from the
4509 * VMCB page. Do not include the encryption mask on the VMSA physical
4510 * address since hardware will access it using the guest key. Note,
4511 * the VMSA will be NULL if this vCPU is the destination for intrahost
4512 * migration, and will be copied later.
4513 */
4514 if (svm->sev_es.vmsa && !svm->sev_es.snp_has_guest_vmsa)
4515 svm->vmcb->control.vmsa_pa = __pa(svm->sev_es.vmsa);
4516
4517 /* Can't intercept CR register access, HV can't modify CR registers */
4518 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
4519 svm_clr_intercept(svm, INTERCEPT_CR4_READ);
4520 svm_clr_intercept(svm, INTERCEPT_CR8_READ);
4521 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
4522 svm_clr_intercept(svm, INTERCEPT_CR4_WRITE);
4523 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
4524
4525 svm_clr_intercept(svm, INTERCEPT_SELECTIVE_CR0);
4526
4527 /* Track EFER/CR register changes */
4528 svm_set_intercept(svm, TRAP_EFER_WRITE);
4529 svm_set_intercept(svm, TRAP_CR0_WRITE);
4530 svm_set_intercept(svm, TRAP_CR4_WRITE);
4531 svm_set_intercept(svm, TRAP_CR8_WRITE);
4532
4533 vmcb->control.intercepts[INTERCEPT_DR] = 0;
4534 if (!sev_vcpu_has_debug_swap(svm)) {
4535 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
4536 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
4537 recalc_intercepts(svm);
4538 } else {
4539 /*
4540 * Disable #DB intercept iff DebugSwap is enabled. KVM doesn't
4541 * allow debugging SEV-ES guests, and enables DebugSwap iff
4542 * NO_NESTED_DATA_BP is supported, so there's no reason to
4543 * intercept #DB when DebugSwap is enabled. For simplicity
4544 * with respect to guest debug, intercept #DB for other VMs
4545 * even if NO_NESTED_DATA_BP is supported, i.e. even if the
4546 * guest can't DoS the CPU with infinite #DB vectoring.
4547 */
4548 clr_exception_intercept(svm, DB_VECTOR);
4549 }
4550
4551 /* Can't intercept XSETBV, HV can't modify XCR0 directly */
4552 svm_clr_intercept(svm, INTERCEPT_XSETBV);
4553
4554 /* Clear intercepts on selected MSRs */
4555 set_msr_interception(vcpu, svm->msrpm, MSR_EFER, 1, 1);
4556 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_CR_PAT, 1, 1);
4557 }
4558
sev_init_vmcb(struct vcpu_svm * svm)4559 void sev_init_vmcb(struct vcpu_svm *svm)
4560 {
4561 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
4562 clr_exception_intercept(svm, UD_VECTOR);
4563
4564 /*
4565 * Don't intercept #GP for SEV guests, e.g. for the VMware backdoor, as
4566 * KVM can't decrypt guest memory to decode the faulting instruction.
4567 */
4568 clr_exception_intercept(svm, GP_VECTOR);
4569
4570 if (sev_es_guest(svm->vcpu.kvm))
4571 sev_es_init_vmcb(svm);
4572 }
4573
sev_es_vcpu_reset(struct vcpu_svm * svm)4574 void sev_es_vcpu_reset(struct vcpu_svm *svm)
4575 {
4576 struct kvm_vcpu *vcpu = &svm->vcpu;
4577 struct kvm_sev_info *sev = &to_kvm_svm(vcpu->kvm)->sev_info;
4578
4579 /*
4580 * Set the GHCB MSR value as per the GHCB specification when emulating
4581 * vCPU RESET for an SEV-ES guest.
4582 */
4583 set_ghcb_msr(svm, GHCB_MSR_SEV_INFO((__u64)sev->ghcb_version,
4584 GHCB_VERSION_MIN,
4585 sev_enc_bit));
4586
4587 mutex_init(&svm->sev_es.snp_vmsa_mutex);
4588 }
4589
sev_es_prepare_switch_to_guest(struct vcpu_svm * svm,struct sev_es_save_area * hostsa)4590 void sev_es_prepare_switch_to_guest(struct vcpu_svm *svm, struct sev_es_save_area *hostsa)
4591 {
4592 struct kvm *kvm = svm->vcpu.kvm;
4593
4594 /*
4595 * All host state for SEV-ES guests is categorized into three swap types
4596 * based on how it is handled by hardware during a world switch:
4597 *
4598 * A: VMRUN: Host state saved in host save area
4599 * VMEXIT: Host state loaded from host save area
4600 *
4601 * B: VMRUN: Host state _NOT_ saved in host save area
4602 * VMEXIT: Host state loaded from host save area
4603 *
4604 * C: VMRUN: Host state _NOT_ saved in host save area
4605 * VMEXIT: Host state initialized to default(reset) values
4606 *
4607 * Manually save type-B state, i.e. state that is loaded by VMEXIT but
4608 * isn't saved by VMRUN, that isn't already saved by VMSAVE (performed
4609 * by common SVM code).
4610 */
4611 hostsa->xcr0 = kvm_host.xcr0;
4612 hostsa->pkru = read_pkru();
4613 hostsa->xss = kvm_host.xss;
4614
4615 /*
4616 * If DebugSwap is enabled, debug registers are loaded but NOT saved by
4617 * the CPU (Type-B). If DebugSwap is disabled/unsupported, the CPU does
4618 * not save or load debug registers. Sadly, KVM can't prevent SNP
4619 * guests from lying about DebugSwap on secondary vCPUs, i.e. the
4620 * SEV_FEATURES provided at "AP Create" isn't guaranteed to match what
4621 * the guest has actually enabled (or not!) in the VMSA.
4622 *
4623 * If DebugSwap is *possible*, save the masks so that they're restored
4624 * if the guest enables DebugSwap. But for the DRs themselves, do NOT
4625 * rely on the CPU to restore the host values; KVM will restore them as
4626 * needed in common code, via hw_breakpoint_restore(). Note, KVM does
4627 * NOT support virtualizing Breakpoint Extensions, i.e. the mask MSRs
4628 * don't need to be restored per se, KVM just needs to ensure they are
4629 * loaded with the correct values *if* the CPU writes the MSRs.
4630 */
4631 if (sev_vcpu_has_debug_swap(svm) ||
4632 (sev_snp_guest(kvm) && cpu_feature_enabled(X86_FEATURE_DEBUG_SWAP))) {
4633 hostsa->dr0_addr_mask = amd_get_dr_addr_mask(0);
4634 hostsa->dr1_addr_mask = amd_get_dr_addr_mask(1);
4635 hostsa->dr2_addr_mask = amd_get_dr_addr_mask(2);
4636 hostsa->dr3_addr_mask = amd_get_dr_addr_mask(3);
4637 }
4638 }
4639
sev_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)4640 void sev_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4641 {
4642 struct vcpu_svm *svm = to_svm(vcpu);
4643
4644 /* First SIPI: Use the values as initially set by the VMM */
4645 if (!svm->sev_es.received_first_sipi) {
4646 svm->sev_es.received_first_sipi = true;
4647 return;
4648 }
4649
4650 /* Subsequent SIPI */
4651 switch (svm->sev_es.ap_reset_hold_type) {
4652 case AP_RESET_HOLD_NAE_EVENT:
4653 /*
4654 * Return from an AP Reset Hold VMGEXIT, where the guest will
4655 * set the CS and RIP. Set SW_EXIT_INFO_2 to a non-zero value.
4656 */
4657 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb, 1);
4658 break;
4659 case AP_RESET_HOLD_MSR_PROTO:
4660 /*
4661 * Return from an AP Reset Hold VMGEXIT, where the guest will
4662 * set the CS and RIP. Set GHCB data field to a non-zero value.
4663 */
4664 set_ghcb_msr_bits(svm, 1,
4665 GHCB_MSR_AP_RESET_HOLD_RESULT_MASK,
4666 GHCB_MSR_AP_RESET_HOLD_RESULT_POS);
4667
4668 set_ghcb_msr_bits(svm, GHCB_MSR_AP_RESET_HOLD_RESP,
4669 GHCB_MSR_INFO_MASK,
4670 GHCB_MSR_INFO_POS);
4671 break;
4672 default:
4673 break;
4674 }
4675 }
4676
snp_safe_alloc_page_node(int node,gfp_t gfp)4677 struct page *snp_safe_alloc_page_node(int node, gfp_t gfp)
4678 {
4679 unsigned long pfn;
4680 struct page *p;
4681
4682 if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
4683 return alloc_pages_node(node, gfp | __GFP_ZERO, 0);
4684
4685 /*
4686 * Allocate an SNP-safe page to workaround the SNP erratum where
4687 * the CPU will incorrectly signal an RMP violation #PF if a
4688 * hugepage (2MB or 1GB) collides with the RMP entry of a
4689 * 2MB-aligned VMCB, VMSA, or AVIC backing page.
4690 *
4691 * Allocate one extra page, choose a page which is not
4692 * 2MB-aligned, and free the other.
4693 */
4694 p = alloc_pages_node(node, gfp | __GFP_ZERO, 1);
4695 if (!p)
4696 return NULL;
4697
4698 split_page(p, 1);
4699
4700 pfn = page_to_pfn(p);
4701 if (IS_ALIGNED(pfn, PTRS_PER_PMD))
4702 __free_page(p++);
4703 else
4704 __free_page(p + 1);
4705
4706 return p;
4707 }
4708
sev_handle_rmp_fault(struct kvm_vcpu * vcpu,gpa_t gpa,u64 error_code)4709 void sev_handle_rmp_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
4710 {
4711 struct kvm_memory_slot *slot;
4712 struct kvm *kvm = vcpu->kvm;
4713 int order, rmp_level, ret;
4714 struct page *page;
4715 bool assigned;
4716 kvm_pfn_t pfn;
4717 gfn_t gfn;
4718
4719 gfn = gpa >> PAGE_SHIFT;
4720
4721 /*
4722 * The only time RMP faults occur for shared pages is when the guest is
4723 * triggering an RMP fault for an implicit page-state change from
4724 * shared->private. Implicit page-state changes are forwarded to
4725 * userspace via KVM_EXIT_MEMORY_FAULT events, however, so RMP faults
4726 * for shared pages should not end up here.
4727 */
4728 if (!kvm_mem_is_private(kvm, gfn)) {
4729 pr_warn_ratelimited("SEV: Unexpected RMP fault for non-private GPA 0x%llx\n",
4730 gpa);
4731 return;
4732 }
4733
4734 slot = gfn_to_memslot(kvm, gfn);
4735 if (!kvm_slot_can_be_private(slot)) {
4736 pr_warn_ratelimited("SEV: Unexpected RMP fault, non-private slot for GPA 0x%llx\n",
4737 gpa);
4738 return;
4739 }
4740
4741 ret = kvm_gmem_get_pfn(kvm, slot, gfn, &pfn, &page, &order);
4742 if (ret) {
4743 pr_warn_ratelimited("SEV: Unexpected RMP fault, no backing page for private GPA 0x%llx\n",
4744 gpa);
4745 return;
4746 }
4747
4748 ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
4749 if (ret || !assigned) {
4750 pr_warn_ratelimited("SEV: Unexpected RMP fault, no assigned RMP entry found for GPA 0x%llx PFN 0x%llx error %d\n",
4751 gpa, pfn, ret);
4752 goto out_no_trace;
4753 }
4754
4755 /*
4756 * There are 2 cases where a PSMASH may be needed to resolve an #NPF
4757 * with PFERR_GUEST_RMP_BIT set:
4758 *
4759 * 1) RMPADJUST/PVALIDATE can trigger an #NPF with PFERR_GUEST_SIZEM
4760 * bit set if the guest issues them with a smaller granularity than
4761 * what is indicated by the page-size bit in the 2MB RMP entry for
4762 * the PFN that backs the GPA.
4763 *
4764 * 2) Guest access via NPT can trigger an #NPF if the NPT mapping is
4765 * smaller than what is indicated by the 2MB RMP entry for the PFN
4766 * that backs the GPA.
4767 *
4768 * In both these cases, the corresponding 2M RMP entry needs to
4769 * be PSMASH'd to 512 4K RMP entries. If the RMP entry is already
4770 * split into 4K RMP entries, then this is likely a spurious case which
4771 * can occur when there are concurrent accesses by the guest to a 2MB
4772 * GPA range that is backed by a 2MB-aligned PFN who's RMP entry is in
4773 * the process of being PMASH'd into 4K entries. These cases should
4774 * resolve automatically on subsequent accesses, so just ignore them
4775 * here.
4776 */
4777 if (rmp_level == PG_LEVEL_4K)
4778 goto out;
4779
4780 ret = snp_rmptable_psmash(pfn);
4781 if (ret) {
4782 /*
4783 * Look it up again. If it's 4K now then the PSMASH may have
4784 * raced with another process and the issue has already resolved
4785 * itself.
4786 */
4787 if (!snp_lookup_rmpentry(pfn, &assigned, &rmp_level) &&
4788 assigned && rmp_level == PG_LEVEL_4K)
4789 goto out;
4790
4791 pr_warn_ratelimited("SEV: Unable to split RMP entry for GPA 0x%llx PFN 0x%llx ret %d\n",
4792 gpa, pfn, ret);
4793 }
4794
4795 kvm_zap_gfn_range(kvm, gfn, gfn + PTRS_PER_PMD);
4796 out:
4797 trace_kvm_rmp_fault(vcpu, gpa, pfn, error_code, rmp_level, ret);
4798 out_no_trace:
4799 kvm_release_page_unused(page);
4800 }
4801
is_pfn_range_shared(kvm_pfn_t start,kvm_pfn_t end)4802 static bool is_pfn_range_shared(kvm_pfn_t start, kvm_pfn_t end)
4803 {
4804 kvm_pfn_t pfn = start;
4805
4806 while (pfn < end) {
4807 int ret, rmp_level;
4808 bool assigned;
4809
4810 ret = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
4811 if (ret) {
4812 pr_warn_ratelimited("SEV: Failed to retrieve RMP entry: PFN 0x%llx GFN start 0x%llx GFN end 0x%llx RMP level %d error %d\n",
4813 pfn, start, end, rmp_level, ret);
4814 return false;
4815 }
4816
4817 if (assigned) {
4818 pr_debug("%s: overlap detected, PFN 0x%llx start 0x%llx end 0x%llx RMP level %d\n",
4819 __func__, pfn, start, end, rmp_level);
4820 return false;
4821 }
4822
4823 pfn++;
4824 }
4825
4826 return true;
4827 }
4828
max_level_for_order(int order)4829 static u8 max_level_for_order(int order)
4830 {
4831 if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
4832 return PG_LEVEL_2M;
4833
4834 return PG_LEVEL_4K;
4835 }
4836
is_large_rmp_possible(struct kvm * kvm,kvm_pfn_t pfn,int order)4837 static bool is_large_rmp_possible(struct kvm *kvm, kvm_pfn_t pfn, int order)
4838 {
4839 kvm_pfn_t pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD);
4840
4841 /*
4842 * If this is a large folio, and the entire 2M range containing the
4843 * PFN is currently shared, then the entire 2M-aligned range can be
4844 * set to private via a single 2M RMP entry.
4845 */
4846 if (max_level_for_order(order) > PG_LEVEL_4K &&
4847 is_pfn_range_shared(pfn_aligned, pfn_aligned + PTRS_PER_PMD))
4848 return true;
4849
4850 return false;
4851 }
4852
sev_gmem_prepare(struct kvm * kvm,kvm_pfn_t pfn,gfn_t gfn,int max_order)4853 int sev_gmem_prepare(struct kvm *kvm, kvm_pfn_t pfn, gfn_t gfn, int max_order)
4854 {
4855 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
4856 kvm_pfn_t pfn_aligned;
4857 gfn_t gfn_aligned;
4858 int level, rc;
4859 bool assigned;
4860
4861 if (!sev_snp_guest(kvm))
4862 return 0;
4863
4864 rc = snp_lookup_rmpentry(pfn, &assigned, &level);
4865 if (rc) {
4866 pr_err_ratelimited("SEV: Failed to look up RMP entry: GFN %llx PFN %llx error %d\n",
4867 gfn, pfn, rc);
4868 return -ENOENT;
4869 }
4870
4871 if (assigned) {
4872 pr_debug("%s: already assigned: gfn %llx pfn %llx max_order %d level %d\n",
4873 __func__, gfn, pfn, max_order, level);
4874 return 0;
4875 }
4876
4877 if (is_large_rmp_possible(kvm, pfn, max_order)) {
4878 level = PG_LEVEL_2M;
4879 pfn_aligned = ALIGN_DOWN(pfn, PTRS_PER_PMD);
4880 gfn_aligned = ALIGN_DOWN(gfn, PTRS_PER_PMD);
4881 } else {
4882 level = PG_LEVEL_4K;
4883 pfn_aligned = pfn;
4884 gfn_aligned = gfn;
4885 }
4886
4887 rc = rmp_make_private(pfn_aligned, gfn_to_gpa(gfn_aligned), level, sev->asid, false);
4888 if (rc) {
4889 pr_err_ratelimited("SEV: Failed to update RMP entry: GFN %llx PFN %llx level %d error %d\n",
4890 gfn, pfn, level, rc);
4891 return -EINVAL;
4892 }
4893
4894 pr_debug("%s: updated: gfn %llx pfn %llx pfn_aligned %llx max_order %d level %d\n",
4895 __func__, gfn, pfn, pfn_aligned, max_order, level);
4896
4897 return 0;
4898 }
4899
sev_gmem_invalidate(kvm_pfn_t start,kvm_pfn_t end)4900 void sev_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end)
4901 {
4902 kvm_pfn_t pfn;
4903
4904 if (!cc_platform_has(CC_ATTR_HOST_SEV_SNP))
4905 return;
4906
4907 pr_debug("%s: PFN start 0x%llx PFN end 0x%llx\n", __func__, start, end);
4908
4909 for (pfn = start; pfn < end;) {
4910 bool use_2m_update = false;
4911 int rc, rmp_level;
4912 bool assigned;
4913
4914 rc = snp_lookup_rmpentry(pfn, &assigned, &rmp_level);
4915 if (rc || !assigned)
4916 goto next_pfn;
4917
4918 use_2m_update = IS_ALIGNED(pfn, PTRS_PER_PMD) &&
4919 end >= (pfn + PTRS_PER_PMD) &&
4920 rmp_level > PG_LEVEL_4K;
4921
4922 /*
4923 * If an unaligned PFN corresponds to a 2M region assigned as a
4924 * large page in the RMP table, PSMASH the region into individual
4925 * 4K RMP entries before attempting to convert a 4K sub-page.
4926 */
4927 if (!use_2m_update && rmp_level > PG_LEVEL_4K) {
4928 /*
4929 * This shouldn't fail, but if it does, report it, but
4930 * still try to update RMP entry to shared and pray this
4931 * was a spurious error that can be addressed later.
4932 */
4933 rc = snp_rmptable_psmash(pfn);
4934 WARN_ONCE(rc, "SEV: Failed to PSMASH RMP entry for PFN 0x%llx error %d\n",
4935 pfn, rc);
4936 }
4937
4938 rc = rmp_make_shared(pfn, use_2m_update ? PG_LEVEL_2M : PG_LEVEL_4K);
4939 if (WARN_ONCE(rc, "SEV: Failed to update RMP entry for PFN 0x%llx error %d\n",
4940 pfn, rc))
4941 goto next_pfn;
4942
4943 /*
4944 * SEV-ES avoids host/guest cache coherency issues through
4945 * WBINVD hooks issued via MMU notifiers during run-time, and
4946 * KVM's VM destroy path at shutdown. Those MMU notifier events
4947 * don't cover gmem since there is no requirement to map pages
4948 * to a HVA in order to use them for a running guest. While the
4949 * shutdown path would still likely cover things for SNP guests,
4950 * userspace may also free gmem pages during run-time via
4951 * hole-punching operations on the guest_memfd, so flush the
4952 * cache entries for these pages before free'ing them back to
4953 * the host.
4954 */
4955 clflush_cache_range(__va(pfn_to_hpa(pfn)),
4956 use_2m_update ? PMD_SIZE : PAGE_SIZE);
4957 next_pfn:
4958 pfn += use_2m_update ? PTRS_PER_PMD : 1;
4959 cond_resched();
4960 }
4961 }
4962
sev_private_max_mapping_level(struct kvm * kvm,kvm_pfn_t pfn)4963 int sev_private_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn)
4964 {
4965 int level, rc;
4966 bool assigned;
4967
4968 if (!sev_snp_guest(kvm))
4969 return 0;
4970
4971 rc = snp_lookup_rmpentry(pfn, &assigned, &level);
4972 if (rc || !assigned)
4973 return PG_LEVEL_4K;
4974
4975 return level;
4976 }
4977