xref: /linux/tools/testing/selftests/ublk/utils.h (revision 22c55fb9eb92395d999b8404d73e58540d11bdd8)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef KUBLK_UTILS_H
3 #define KUBLK_UTILS_H
4 
5 #define __maybe_unused __attribute__((unused))
6 
7 #ifndef min
8 #define min(a, b) ((a) < (b) ? (a) : (b))
9 #endif
10 
11 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
12 
13 #ifndef offsetof
14 #define offsetof(TYPE, MEMBER)  ((size_t)&((TYPE *)0)->MEMBER)
15 #endif
16 
17 #ifndef container_of
18 #define container_of(ptr, type, member) ({                              \
19 	unsigned long __mptr = (unsigned long)(ptr);                    \
20 	((type *)(__mptr - offsetof(type, member))); })
21 #endif
22 
23 #define round_up(val, rnd) \
24 	(((val) + ((rnd) - 1)) & ~((rnd) - 1))
25 
26 static inline unsigned int ilog2(unsigned int x)
27 {
28 	if (x == 0)
29 		return 0;
30 	return (sizeof(x) * 8 - 1) - __builtin_clz(x);
31 }
32 
33 #define UBLK_DBG_DEV            (1U << 0)
34 #define UBLK_DBG_THREAD         (1U << 1)
35 #define UBLK_DBG_IO_CMD         (1U << 2)
36 #define UBLK_DBG_IO             (1U << 3)
37 #define UBLK_DBG_CTRL_CMD       (1U << 4)
38 #define UBLK_LOG                (1U << 5)
39 
40 extern unsigned int ublk_dbg_mask;
41 
42 static inline void ublk_err(const char *fmt, ...)
43 {
44 	va_list ap;
45 
46 	va_start(ap, fmt);
47 	vfprintf(stderr, fmt, ap);
48 }
49 
50 static inline void ublk_log(const char *fmt, ...)
51 {
52 	if (ublk_dbg_mask & UBLK_LOG) {
53 		va_list ap;
54 
55 		va_start(ap, fmt);
56 		vfprintf(stdout, fmt, ap);
57 	}
58 }
59 
60 static inline void ublk_dbg(int level, const char *fmt, ...)
61 {
62 	if (level & ublk_dbg_mask) {
63 		va_list ap;
64 
65 		va_start(ap, fmt);
66 		vfprintf(stdout, fmt, ap);
67 	}
68 }
69 
70 #endif
71