diff mbox series

[V3,3/8] KVM: selftests: x86: Support changing gpa encryption masks

Message ID 20221223001352.3873203-4-vannapurve@google.com
State New
Headers show
Series KVM: selftests: SEV: selftests for fd-based private memory | expand

Commit Message

Vishal Annapurve Dec. 23, 2022, 12:13 a.m. UTC
Add support for guest side functionality to modify encryption/shared
masks for entries in page table to allow accessing GPA ranges as private
or shared.

Signed-off-by: Vishal Annapurve <vannapurve@google.com>
---
 .../selftests/kvm/include/x86_64/processor.h  |  4 ++
 .../selftests/kvm/lib/x86_64/processor.c      | 39 +++++++++++++++++++
 2 files changed, 43 insertions(+)
diff mbox series

Patch

diff --git a/tools/testing/selftests/kvm/include/x86_64/processor.h b/tools/testing/selftests/kvm/include/x86_64/processor.h
index 3617f83bb2e5..c8c55f54c14f 100644
--- a/tools/testing/selftests/kvm/include/x86_64/processor.h
+++ b/tools/testing/selftests/kvm/include/x86_64/processor.h
@@ -945,6 +945,10 @@  void vcpu_init_descriptor_tables(struct kvm_vcpu *vcpu);
 void vm_install_exception_handler(struct kvm_vm *vm, int vector,
 			void (*handler)(struct ex_regs *));
 
+void guest_set_region_shared(void *vaddr, uint64_t size);
+
+void guest_set_region_private(void *vaddr, uint64_t size);
+
 /* If a toddler were to say "abracadabra". */
 #define KVM_EXCEPTION_MAGIC 0xabacadabaULL
 
diff --git a/tools/testing/selftests/kvm/lib/x86_64/processor.c b/tools/testing/selftests/kvm/lib/x86_64/processor.c
index ab7d4cc4b848..42d1e4074f32 100644
--- a/tools/testing/selftests/kvm/lib/x86_64/processor.c
+++ b/tools/testing/selftests/kvm/lib/x86_64/processor.c
@@ -276,6 +276,45 @@  static uint64_t *guest_code_get_pte(uint64_t vaddr)
 	return (uint64_t *)&pte[index[0]];
 }
 
+static void guest_code_change_region_prot(void *vaddr_start, uint64_t mem_size,
+	bool private)
+{
+	uint64_t vaddr = (uint64_t)vaddr_start;
+	uint32_t num_pages;
+
+	GUEST_ASSERT(gpgt_info != NULL);
+	uint32_t guest_page_size = gpgt_info->page_size;
+
+	GUEST_ASSERT(!(mem_size % guest_page_size) && !(vaddr % guest_page_size));
+	GUEST_ASSERT(gpgt_info->enc_mask | gpgt_info->shared_mask);
+
+	num_pages = mem_size / guest_page_size;
+	for (uint32_t i = 0; i < num_pages; i++) {
+		uint64_t *pte = guest_code_get_pte(vaddr);
+
+		GUEST_ASSERT(pte);
+		if (private) {
+			*pte &= ~(gpgt_info->shared_mask);
+			*pte |= gpgt_info->enc_mask;
+		} else {
+			*pte &= ~(gpgt_info->enc_mask);
+			*pte |= gpgt_info->shared_mask;
+		}
+		asm volatile("invlpg (%0)" :: "r"(vaddr) : "memory");
+		vaddr += guest_page_size;
+	}
+}
+
+void guest_set_region_shared(void *vaddr, uint64_t size)
+{
+	guest_code_change_region_prot(vaddr, size, /* shared */ false);
+}
+
+void guest_set_region_private(void *vaddr, uint64_t size)
+{
+	guest_code_change_region_prot(vaddr, size, /* private */ true);
+}
+
 void sync_vm_gpgt_info(struct kvm_vm *vm, vm_vaddr_t pgt_info)
 {
 	gpgt_info = (struct guest_pgt_info *)pgt_info;