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