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_arch_init(struct kvm_vm *vm, vm_paddr_t mmio_gpa)
14 {
15 }
16 
17 struct sbiret sbi_ecall(int ext, int fid, unsigned long arg0,
18 			unsigned long arg1, unsigned long arg2,
19 			unsigned long arg3, unsigned long arg4,
20 			unsigned long arg5)
21 {
22 	register uintptr_t a0 asm ("a0") = (uintptr_t)(arg0);
23 	register uintptr_t a1 asm ("a1") = (uintptr_t)(arg1);
24 	register uintptr_t a2 asm ("a2") = (uintptr_t)(arg2);
25 	register uintptr_t a3 asm ("a3") = (uintptr_t)(arg3);
26 	register uintptr_t a4 asm ("a4") = (uintptr_t)(arg4);
27 	register uintptr_t a5 asm ("a5") = (uintptr_t)(arg5);
28 	register uintptr_t a6 asm ("a6") = (uintptr_t)(fid);
29 	register uintptr_t a7 asm ("a7") = (uintptr_t)(ext);
30 	struct sbiret ret;
31 
32 	asm volatile (
33 		"ecall"
34 		: "+r" (a0), "+r" (a1)
35 		: "r" (a2), "r" (a3), "r" (a4), "r" (a5), "r" (a6), "r" (a7)
36 		: "memory");
37 	ret.error = a0;
38 	ret.value = a1;
39 
40 	return ret;
41 }
42 
43 void ucall_arch_do_ucall(vm_vaddr_t uc)
44 {
45 	sbi_ecall(KVM_RISCV_SELFTESTS_SBI_EXT,
46 		  KVM_RISCV_SELFTESTS_SBI_UCALL,
47 		  uc, 0, 0, 0, 0, 0);
48 }
49 
50 void *ucall_arch_get_ucall(struct kvm_vcpu *vcpu)
51 {
52 	struct kvm_run *run = vcpu->run;
53 
54 	if (run->exit_reason == KVM_EXIT_RISCV_SBI &&
55 	    run->riscv_sbi.extension_id == KVM_RISCV_SELFTESTS_SBI_EXT) {
56 		switch (run->riscv_sbi.function_id) {
57 		case KVM_RISCV_SELFTESTS_SBI_UCALL:
58 			return (void *)run->riscv_sbi.args[0];
59 		case KVM_RISCV_SELFTESTS_SBI_UNEXP:
60 			vcpu_dump(stderr, vcpu, 2);
61 			TEST_ASSERT(0, "Unexpected trap taken by guest");
62 			break;
63 		default:
64 			break;
65 		}
66 	}
67 	return NULL;
68 }
69