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