1 // SPDX-License-Identifier: GPL-2.0-only
3 #include "linux/types.h"
4 #include "linux/bitmap.h"
5 #include "linux/atomic.h"
7 #define GUEST_UCALL_FAILED -1
10 DECLARE_BITMAP(in_use, KVM_MAX_VCPUS);
11 struct ucall ucalls[KVM_MAX_VCPUS];
15 * ucall_pool holds per-VM values (global data is duplicated by each VM), it
16 * must not be accessed from host code.
18 static struct ucall_header *ucall_pool;
20 void ucall_init(struct kvm_vm *vm, vm_paddr_t mmio_gpa)
22 struct ucall_header *hdr;
27 vaddr = __vm_vaddr_alloc(vm, sizeof(*hdr), KVM_UTIL_MIN_VADDR, MEM_REGION_DATA);
28 hdr = (struct ucall_header *)addr_gva2hva(vm, vaddr);
29 memset(hdr, 0, sizeof(*hdr));
31 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
36 write_guest_global(vm, ucall_pool, (struct ucall_header *)vaddr);
38 ucall_arch_init(vm, mmio_gpa);
41 static struct ucall *ucall_alloc(void)
49 for (i = 0; i < KVM_MAX_VCPUS; ++i) {
50 if (!test_and_set_bit(i, ucall_pool->in_use)) {
51 uc = &ucall_pool->ucalls[i];
52 memset(uc->args, 0, sizeof(uc->args));
59 * If the vCPU cannot grab a ucall structure, make a bare ucall with a
60 * magic value to signal to get_ucall() that things went sideways.
61 * GUEST_ASSERT() depends on ucall_alloc() and so cannot be used here.
63 ucall_arch_do_ucall(GUEST_UCALL_FAILED);
67 static void ucall_free(struct ucall *uc)
69 /* Beware, here be pointer arithmetic. */
70 clear_bit(uc - ucall_pool->ucalls, ucall_pool->in_use);
73 void ucall(uint64_t cmd, int nargs, ...)
81 WRITE_ONCE(uc->cmd, cmd);
83 nargs = min(nargs, UCALL_MAX_ARGS);
86 for (i = 0; i < nargs; ++i)
87 WRITE_ONCE(uc->args[i], va_arg(va, uint64_t));
90 ucall_arch_do_ucall((vm_vaddr_t)uc->hva);
95 uint64_t get_ucall(struct kvm_vcpu *vcpu, struct ucall *uc)
103 addr = ucall_arch_get_ucall(vcpu);
105 TEST_ASSERT(addr != (void *)GUEST_UCALL_FAILED,
106 "Guest failed to allocate ucall struct");
108 memcpy(uc, addr, sizeof(*uc));
109 vcpu_run_complete_io(vcpu);
111 memset(uc, 0, sizeof(*uc));