xref: /linux-6.15/tools/include/linux/kernel.h (revision fcc8487d)
1 #ifndef __TOOLS_LINUX_KERNEL_H
2 #define __TOOLS_LINUX_KERNEL_H
3 
4 #include <stdarg.h>
5 #include <stddef.h>
6 #include <assert.h>
7 #include <linux/compiler.h>
8 
9 #ifndef UINT_MAX
10 #define UINT_MAX	(~0U)
11 #endif
12 
13 #define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
14 
15 #define PERF_ALIGN(x, a)	__PERF_ALIGN_MASK(x, (typeof(x))(a)-1)
16 #define __PERF_ALIGN_MASK(x, mask)	(((x)+(mask))&~(mask))
17 
18 #ifndef offsetof
19 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
20 #endif
21 
22 #ifndef container_of
23 /**
24  * container_of - cast a member of a structure out to the containing structure
25  * @ptr:	the pointer to the member.
26  * @type:	the type of the container struct this is embedded in.
27  * @member:	the name of the member within the struct.
28  *
29  */
30 #define container_of(ptr, type, member) ({			\
31 	const typeof(((type *)0)->member) * __mptr = (ptr);	\
32 	(type *)((char *)__mptr - offsetof(type, member)); })
33 #endif
34 
35 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
36 
37 #ifndef max
38 #define max(x, y) ({				\
39 	typeof(x) _max1 = (x);			\
40 	typeof(y) _max2 = (y);			\
41 	(void) (&_max1 == &_max2);		\
42 	_max1 > _max2 ? _max1 : _max2; })
43 #endif
44 
45 #ifndef min
46 #define min(x, y) ({				\
47 	typeof(x) _min1 = (x);			\
48 	typeof(y) _min2 = (y);			\
49 	(void) (&_min1 == &_min2);		\
50 	_min1 < _min2 ? _min1 : _min2; })
51 #endif
52 
53 #ifndef roundup
54 #define roundup(x, y) (                                \
55 {                                                      \
56 	const typeof(y) __y = y;		       \
57 	(((x) + (__y - 1)) / __y) * __y;	       \
58 }                                                      \
59 )
60 #endif
61 
62 #ifndef BUG_ON
63 #ifdef NDEBUG
64 #define BUG_ON(cond) do { if (cond) {} } while (0)
65 #else
66 #define BUG_ON(cond) assert(!(cond))
67 #endif
68 #endif
69 
70 /*
71  * Both need more care to handle endianness
72  * (Don't use bitmap_copy_le() for now)
73  */
74 #define cpu_to_le64(x)	(x)
75 #define cpu_to_le32(x)	(x)
76 
77 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args);
78 int scnprintf(char * buf, size_t size, const char * fmt, ...);
79 
80 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
81 
82 /*
83  * This looks more complex than it should be. But we need to
84  * get the type for the ~ right in round_down (it needs to be
85  * as wide as the result!), and we want to evaluate the macro
86  * arguments just once each.
87  */
88 #define __round_mask(x, y) ((__typeof__(x))((y)-1))
89 #define round_up(x, y) ((((x)-1) | __round_mask(x, y))+1)
90 #define round_down(x, y) ((x) & ~__round_mask(x, y))
91 
92 #endif
93