1 /* SPDX-License-Identifier: GPL-2.0-only */
2 #ifndef SELFTEST_KVM_SYSCALLS_H
3 #define SELFTEST_KVM_SYSCALLS_H
4
5 #include <sys/syscall.h>
6
7 #define MAP_ARGS0(m,...)
8 #define MAP_ARGS1(m,t,a,...) m(t,a)
9 #define MAP_ARGS2(m,t,a,...) m(t,a), MAP_ARGS1(m,__VA_ARGS__)
10 #define MAP_ARGS3(m,t,a,...) m(t,a), MAP_ARGS2(m,__VA_ARGS__)
11 #define MAP_ARGS4(m,t,a,...) m(t,a), MAP_ARGS3(m,__VA_ARGS__)
12 #define MAP_ARGS5(m,t,a,...) m(t,a), MAP_ARGS4(m,__VA_ARGS__)
13 #define MAP_ARGS6(m,t,a,...) m(t,a), MAP_ARGS5(m,__VA_ARGS__)
14 #define MAP_ARGS(n,...) MAP_ARGS##n(__VA_ARGS__)
15
16 #define __DECLARE_ARGS(t, a) t a
17 #define __UNPACK_ARGS(t, a) a
18
19 #define DECLARE_ARGS(nr_args, args...) MAP_ARGS(nr_args, __DECLARE_ARGS, args)
20 #define UNPACK_ARGS(nr_args, args...) MAP_ARGS(nr_args, __UNPACK_ARGS, args)
21
22 #define __KVM_SYSCALL_ERROR(_name, _ret) \
23 "%s failed, rc: %i errno: %i (%s)", (_name), (_ret), errno, strerror(errno)
24
25 /* Define a kvm_<syscall>() API to assert success. */
26 #define __KVM_SYSCALL_DEFINE(name, nr_args, args...) \
27 static inline void kvm_##name(DECLARE_ARGS(nr_args, args)) \
28 { \
29 int r; \
30 \
31 r = name(UNPACK_ARGS(nr_args, args)); \
32 TEST_ASSERT(!r, __KVM_SYSCALL_ERROR(#name, r)); \
33 }
34
35 /*
36 * Macro to define syscall APIs, either because KVM selftests doesn't link to
37 * the standard library, e.g. libnuma, or because there is no library that yet
38 * provides the syscall. These
39 */
40 #define KVM_SYSCALL_DEFINE(name, nr_args, args...) \
41 static inline long name(DECLARE_ARGS(nr_args, args)) \
42 { \
43 return syscall(__NR_##name, UNPACK_ARGS(nr_args, args)); \
44 } \
45 __KVM_SYSCALL_DEFINE(name, nr_args, args)
46
47 /*
48 * Special case mmap(), as KVM selftest rarely/never specific an address,
49 * rarely specify an offset, and because the unique return code requires
50 * special handling anyways.
51 */
__kvm_mmap(size_t size,int prot,int flags,int fd,off_t offset)52 static inline void *__kvm_mmap(size_t size, int prot, int flags, int fd,
53 off_t offset)
54 {
55 void *mem;
56
57 mem = mmap(NULL, size, prot, flags, fd, offset);
58 TEST_ASSERT(mem != MAP_FAILED, __KVM_SYSCALL_ERROR("mmap()",
59 (int)(unsigned long)MAP_FAILED));
60 return mem;
61 }
62
kvm_mmap(size_t size,int prot,int flags,int fd)63 static inline void *kvm_mmap(size_t size, int prot, int flags, int fd)
64 {
65 return __kvm_mmap(size, prot, flags, fd, 0);
66 }
67
kvm_dup(int fd)68 static inline int kvm_dup(int fd)
69 {
70 int new_fd = dup(fd);
71
72 TEST_ASSERT(new_fd >= 0, __KVM_SYSCALL_ERROR("dup()", new_fd));
73 return new_fd;
74 }
75
76 __KVM_SYSCALL_DEFINE(munmap, 2, void *, mem, size_t, size);
77 __KVM_SYSCALL_DEFINE(close, 1, int, fd);
78 __KVM_SYSCALL_DEFINE(fallocate, 4, int, fd, int, mode, loff_t, offset, loff_t, len);
79 __KVM_SYSCALL_DEFINE(ftruncate, 2, unsigned int, fd, off_t, length);
80
81 #endif /* SELFTEST_KVM_SYSCALLS_H */
82