xref: /kvmtool/include/kvm/util.h (revision f8edca99fb397f085fcb5948e0354e1d1e38ba43)
1 #include <linux/stringify.h>
2 
3 #ifndef KVM__UTIL_H
4 #define KVM__UTIL_H
5 
6 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
7 
8 /*
9  * Some bits are stolen from perf tool :)
10  */
11 
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <stddef.h>
15 #include <stdlib.h>
16 #include <stdarg.h>
17 #include <string.h>
18 #include <stdbool.h>
19 #include <signal.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <sys/param.h>
23 #include <sys/types.h>
24 #include <linux/types.h>
25 
26 #ifdef __GNUC__
27 #define NORETURN __attribute__((__noreturn__))
28 #else
29 #define NORETURN
30 #ifndef __attribute__
31 #define __attribute__(x)
32 #endif
33 #endif
34 
35 extern bool do_debug_print;
36 
37 #define PROT_RW (PROT_READ|PROT_WRITE)
38 #define MAP_ANON_NORESERVE (MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE)
39 
40 extern void die(const char *err, ...) NORETURN __attribute__((format (printf, 1, 2)));
41 extern void die_perror(const char *s) NORETURN;
42 extern int pr_err(const char *err, ...) __attribute__((format (printf, 1, 2)));
43 extern void pr_warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
44 extern void pr_info(const char *err, ...) __attribute__((format (printf, 1, 2)));
45 extern void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN);
46 
47 #define pr_debug(fmt, ...)						\
48 	do {								\
49 		if (do_debug_print)					\
50 			pr_info("(%s) %s:%d: " fmt, __FILE__,		\
51 				__func__, __LINE__, ##__VA_ARGS__);	\
52 	} while (0)
53 
54 
55 #define BUILD_BUG_ON(condition)	((void)sizeof(char[1 - 2*!!(condition)]))
56 
57 #ifndef BUG_ON_HANDLER
58 # define BUG_ON_HANDLER(condition)					\
59 	do {								\
60 		if ((condition)) {					\
61 			pr_err("BUG at %s:%d", __FILE__, __LINE__);	\
62 			raise(SIGABRT);					\
63 		}							\
64 	} while (0)
65 #endif
66 
67 #define BUG_ON(condition)	BUG_ON_HANDLER((condition))
68 
69 #define DIE_IF(cnd)						\
70 do {								\
71 	if (cnd)						\
72 	die(" at (" __FILE__ ":" __stringify(__LINE__) "): "	\
73 		__stringify(cnd) "\n");				\
74 } while (0)
75 
76 #define WARN_ON(condition) ({					\
77 	int __ret_warn_on = !!(condition);			\
78 	if (__ret_warn_on)					\
79 		pr_warning("(%s) %s:%d: failed condition: %s",	\
80 				__FILE__, __func__, __LINE__,	\
81 				__stringify(condition));	\
82 	__ret_warn_on;						\
83 })
84 
85 #define MSECS_TO_USECS(s) ((s) * 1000)
86 
87 /* Millisecond sleep */
88 static inline void msleep(unsigned int msecs)
89 {
90 	usleep(MSECS_TO_USECS(msecs));
91 }
92 
93 void *mmap_anon_or_hugetlbfs(const char *hugetlbfs_path, u64 size);
94 
95 #endif /* KVM__UTIL_H */
96