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 "processor.h"
12 
13 void ucall_init(struct kvm_vm *vm, void *arg)
14 {
15 }
16 
17 void ucall_uninit(struct kvm_vm *vm)
18 {
19 }
20 
21 struct sbiret sbi_ecall(int ext, int fid, unsigned long arg0,
22 			unsigned long arg1, unsigned long arg2,
23 			unsigned long arg3, unsigned long arg4,
24 			unsigned long arg5)
25 {
26 	register uintptr_t a0 asm ("a0") = (uintptr_t)(arg0);
27 	register uintptr_t a1 asm ("a1") = (uintptr_t)(arg1);
28 	register uintptr_t a2 asm ("a2") = (uintptr_t)(arg2);
29 	register uintptr_t a3 asm ("a3") = (uintptr_t)(arg3);
30 	register uintptr_t a4 asm ("a4") = (uintptr_t)(arg4);
31 	register uintptr_t a5 asm ("a5") = (uintptr_t)(arg5);
32 	register uintptr_t a6 asm ("a6") = (uintptr_t)(fid);
33 	register uintptr_t a7 asm ("a7") = (uintptr_t)(ext);
34 	struct sbiret ret;
35 
36 	asm volatile (
37 		"ecall"
38 		: "+r" (a0), "+r" (a1)
39 		: "r" (a2), "r" (a3), "r" (a4), "r" (a5), "r" (a6), "r" (a7)
40 		: "memory");
41 	ret.error = a0;
42 	ret.value = a1;
43 
44 	return ret;
45 }
46 
47 void ucall(uint64_t cmd, int nargs, ...)
48 {
49 	struct ucall uc = {
50 		.cmd = cmd,
51 	};
52 	va_list va;
53 	int i;
54 
55 	nargs = min(nargs, UCALL_MAX_ARGS);
56 
57 	va_start(va, nargs);
58 	for (i = 0; i < nargs; ++i)
59 		uc.args[i] = va_arg(va, uint64_t);
60 	va_end(va);
61 
62 	sbi_ecall(KVM_RISCV_SELFTESTS_SBI_EXT,
63 		  KVM_RISCV_SELFTESTS_SBI_UCALL,
64 		  (vm_vaddr_t)&uc, 0, 0, 0, 0, 0);
65 }
66 
67 uint64_t get_ucall(struct kvm_vcpu *vcpu, struct ucall *uc)
68 {
69 	struct kvm_run *run = vcpu->run;
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 		switch (run->riscv_sbi.function_id) {
78 		case KVM_RISCV_SELFTESTS_SBI_UCALL:
79 			memcpy(&ucall,
80 			       addr_gva2hva(vcpu->vm, run->riscv_sbi.args[0]),
81 			       sizeof(ucall));
82 
83 			vcpu_run_complete_io(vcpu);
84 			if (uc)
85 				memcpy(uc, &ucall, sizeof(ucall));
86 
87 			break;
88 		case KVM_RISCV_SELFTESTS_SBI_UNEXP:
89 			vcpu_dump(stderr, vcpu, 2);
90 			TEST_ASSERT(0, "Unexpected trap taken by guest");
91 			break;
92 		default:
93 			break;
94 		}
95 	}
96 
97 	return ucall.cmd;
98 }
99