1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ucall support. A ucall is a "hypercall to userspace".
4  *
5  * Copyright (C) 2021 Western Digital Corporation or its affiliates.
6  */
7 
8 #include <linux/kvm.h>
9 
10 #include "kvm_util.h"
11 #include "../kvm_util_internal.h"
12 #include "processor.h"
13 
14 void ucall_init(struct kvm_vm *vm, void *arg)
15 {
16 }
17 
18 void ucall_uninit(struct kvm_vm *vm)
19 {
20 }
21 
22 struct sbiret sbi_ecall(int ext, int fid, unsigned long arg0,
23 			unsigned long arg1, unsigned long arg2,
24 			unsigned long arg3, unsigned long arg4,
25 			unsigned long arg5)
26 {
27 	register uintptr_t a0 asm ("a0") = (uintptr_t)(arg0);
28 	register uintptr_t a1 asm ("a1") = (uintptr_t)(arg1);
29 	register uintptr_t a2 asm ("a2") = (uintptr_t)(arg2);
30 	register uintptr_t a3 asm ("a3") = (uintptr_t)(arg3);
31 	register uintptr_t a4 asm ("a4") = (uintptr_t)(arg4);
32 	register uintptr_t a5 asm ("a5") = (uintptr_t)(arg5);
33 	register uintptr_t a6 asm ("a6") = (uintptr_t)(fid);
34 	register uintptr_t a7 asm ("a7") = (uintptr_t)(ext);
35 	struct sbiret ret;
36 
37 	asm volatile (
38 		"ecall"
39 		: "+r" (a0), "+r" (a1)
40 		: "r" (a2), "r" (a3), "r" (a4), "r" (a5), "r" (a6), "r" (a7)
41 		: "memory");
42 	ret.error = a0;
43 	ret.value = a1;
44 
45 	return ret;
46 }
47 
48 void ucall(uint64_t cmd, int nargs, ...)
49 {
50 	struct ucall uc = {
51 		.cmd = cmd,
52 	};
53 	va_list va;
54 	int i;
55 
56 	nargs = nargs <= UCALL_MAX_ARGS ? nargs : UCALL_MAX_ARGS;
57 
58 	va_start(va, nargs);
59 	for (i = 0; i < nargs; ++i)
60 		uc.args[i] = va_arg(va, uint64_t);
61 	va_end(va);
62 
63 	sbi_ecall(KVM_RISCV_SELFTESTS_SBI_EXT, 0, (vm_vaddr_t)&uc,
64 		  0, 0, 0, 0, 0);
65 }
66 
67 uint64_t get_ucall(struct kvm_vm *vm, uint32_t vcpu_id, struct ucall *uc)
68 {
69 	struct kvm_run *run = vcpu_state(vm, vcpu_id);
70 	struct ucall ucall = {};
71 
72 	if (uc)
73 		memset(uc, 0, sizeof(*uc));
74 
75 	if (run->exit_reason == KVM_EXIT_RISCV_SBI &&
76 	    run->riscv_sbi.extension_id == KVM_RISCV_SELFTESTS_SBI_EXT &&
77 	    run->riscv_sbi.function_id == 0) {
78 		memcpy(&ucall, addr_gva2hva(vm, run->riscv_sbi.args[0]),
79 			sizeof(ucall));
80 
81 		vcpu_run_complete_io(vm, vcpu_id);
82 		if (uc)
83 			memcpy(uc, &ucall, sizeof(ucall));
84 	}
85 
86 	return ucall.cmd;
87 }
88