File Index
Files and directories
Sign in
FILE

sev.c

File preview with syntax highlighting.

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