summaryrefslogtreecommitdiffstats
path: root/drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c
blob: 8256cf68fd765f3ec1cc441292fd01a0c06c681b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Support for the hypercall interface exposed to protected guests by
 * pKVM.
 *
 * Author: Will Deacon <will@kernel.org>
 * Copyright (C) 2024 Google LLC
 */

#include <linux/arm-smccc.h>
#include <linux/array_size.h>
#include <linux/mem_encrypt.h>
#include <linux/mm.h>

#include <asm/hypervisor.h>

static size_t pkvm_granule;

static int arm_smccc_do_one_page(u32 func_id, phys_addr_t phys)
{
	phys_addr_t end = phys + PAGE_SIZE;

	while (phys < end) {
		struct arm_smccc_res res;

		arm_smccc_1_1_invoke(func_id, phys, 0, 0, &res);
		if (res.a0 != SMCCC_RET_SUCCESS)
			return -EPERM;

		phys += pkvm_granule;
	}

	return 0;
}

static int __set_memory_range(u32 func_id, unsigned long start, int numpages)
{
	void *addr = (void *)start, *end = addr + numpages * PAGE_SIZE;

	while (addr < end) {
		int err;

		err = arm_smccc_do_one_page(func_id, virt_to_phys(addr));
		if (err)
			return err;

		addr += PAGE_SIZE;
	}

	return 0;
}

static int pkvm_set_memory_encrypted(unsigned long addr, int numpages)
{
	return __set_memory_range(ARM_SMCCC_VENDOR_HYP_KVM_MEM_UNSHARE_FUNC_ID,
				  addr, numpages);
}

static int pkvm_set_memory_decrypted(unsigned long addr, int numpages)
{
	return __set_memory_range(ARM_SMCCC_VENDOR_HYP_KVM_MEM_SHARE_FUNC_ID,
				  addr, numpages);
}

static const struct arm64_mem_crypt_ops pkvm_crypt_ops = {
	.encrypt	= pkvm_set_memory_encrypted,
	.decrypt	= pkvm_set_memory_decrypted,
};

void pkvm_init_hyp_services(void)
{
	int i;
	struct arm_smccc_res res;
	const u32 funcs[] = {
		ARM_SMCCC_KVM_FUNC_HYP_MEMINFO,
		ARM_SMCCC_KVM_FUNC_MEM_SHARE,
		ARM_SMCCC_KVM_FUNC_MEM_UNSHARE,
	};

	for (i = 0; i < ARRAY_SIZE(funcs); ++i) {
		if (!kvm_arm_hyp_service_available(funcs[i]))
			return;
	}

	arm_smccc_1_1_invoke(ARM_SMCCC_VENDOR_HYP_KVM_HYP_MEMINFO_FUNC_ID,
			     0, 0, 0, &res);
	if (res.a0 > PAGE_SIZE) /* Includes error codes */
		return;

	pkvm_granule = res.a0;
	arm64_mem_crypt_ops_register(&pkvm_crypt_ops);
}