xref: /linux-6.15/include/linux/minmax.h (revision b280bb27)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MINMAX_H
3 #define _LINUX_MINMAX_H
4 
5 #include <linux/build_bug.h>
6 #include <linux/compiler.h>
7 #include <linux/const.h>
8 #include <linux/types.h>
9 
10 /*
11  * min()/max()/clamp() macros must accomplish several things:
12  *
13  * - Avoid multiple evaluations of the arguments (so side-effects like
14  *   "x++" happen only once) when non-constant.
15  * - Perform signed v unsigned type-checking (to generate compile
16  *   errors instead of nasty runtime surprises).
17  * - Unsigned char/short are always promoted to signed int and can be
18  *   compared against signed or unsigned arguments.
19  * - Unsigned arguments can be compared against non-negative signed constants.
20  * - Comparison of a signed argument against an unsigned constant fails
21  *   even if the constant is below __INT_MAX__ and could be cast to int.
22  */
23 #define __typecheck(x, y) \
24 	(!!(sizeof((typeof(x) *)1 == (typeof(y) *)1)))
25 
26 /*
27  * __sign_use for integer expressions:
28  *   bit #0 set if ok for unsigned comparisons
29  *   bit #1 set if ok for signed comparisons
30  *
31  * In particular, statically non-negative signed integer expressions
32  * are ok for both.
33  *
34  * NOTE! Unsigned types smaller than 'int' are implicitly converted to 'int'
35  * in expressions, and are accepted for signed conversions for now.
36  * This is debatable.
37  *
38  * Note that 'x' is the original expression, and 'ux' is the unique variable
39  * that contains the value.
40  *
41  * We use 'ux' for pure type checking, and 'x' for when we need to look at the
42  * value (but without evaluating it for side effects!
43  * Careful to only ever evaluate it with sizeof() or __builtin_constant_p() etc).
44  *
45  * Pointers end up being checked by the normal C type rules at the actual
46  * comparison, and these expressions only need to be careful to not cause
47  * warnings for pointer use.
48  */
49 #define __signed_type_use(ux) (2 + __is_nonneg(ux))
50 #define __unsigned_type_use(ux) (1 + 2 * (sizeof(ux) < 4))
51 #define __sign_use(ux) (is_signed_type(typeof(ux)) ? \
52 	__signed_type_use(ux) : __unsigned_type_use(ux))
53 
54 /*
55  * Check whether a signed value is always non-negative.
56  *
57  * A cast is needed to avoid any warnings from values that aren't signed
58  * integer types (in which case the result doesn't matter).
59  *
60  * On 64-bit any integer or pointer type can safely be cast to 'long'.
61  * But on 32-bit we need to avoid warnings about casting pointers to integers
62  * of different sizes without truncating 64-bit values so 'long' or 'long long'
63  * must be used depending on the size of the value.
64  *
65  * This does not work for 128-bit signed integers since the cast would truncate
66  * them, but we do not use s128 types in the kernel (we do use 'u128',
67  * but they are handled by the !is_signed_type() case).
68  */
69 #ifdef CONFIG_64BIT
70   #define __signed_type(ux) long
71 #else
72   #define __signed_type(ux) typeof(__builtin_choose_expr(sizeof(ux) > 4, 1LL, 1L))
73 #endif
74 #define __is_nonneg(ux) statically_true((__signed_type(ux))(ux) >= 0)
75 
76 #define __types_ok(ux, uy) \
77 	(__sign_use(ux) & __sign_use(uy))
78 
79 #define __types_ok3(ux, uy, uz) \
80 	(__sign_use(ux) & __sign_use(uy) & __sign_use(uz))
81 
82 #define __cmp_op_min <
83 #define __cmp_op_max >
84 
85 #define __cmp(op, x, y)	((x) __cmp_op_##op (y) ? (x) : (y))
86 
87 #define __cmp_once_unique(op, type, x, y, ux, uy) \
88 	({ type ux = (x); type uy = (y); __cmp(op, ux, uy); })
89 
90 #define __cmp_once(op, type, x, y) \
91 	__cmp_once_unique(op, type, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
92 
93 #define __careful_cmp_once(op, x, y, ux, uy) ({		\
94 	__auto_type ux = (x); __auto_type uy = (y);	\
95 	BUILD_BUG_ON_MSG(!__types_ok(ux, uy),		\
96 		#op"("#x", "#y") signedness error");	\
97 	__cmp(op, ux, uy); })
98 
99 #define __careful_cmp(op, x, y) \
100 	__careful_cmp_once(op, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
101 
102 #define __clamp(val, lo, hi)	\
103 	((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
104 
105 #define __clamp_once(val, lo, hi, uval, ulo, uhi) ({				\
106 	__auto_type uval = (val);						\
107 	__auto_type ulo = (lo);							\
108 	__auto_type uhi = (hi);							\
109 	static_assert(__builtin_choose_expr(__is_constexpr((lo) > (hi)), 	\
110 			(lo) <= (hi), true),					\
111 		"clamp() low limit " #lo " greater than high limit " #hi);	\
112 	BUILD_BUG_ON_MSG(!__types_ok3(uval, ulo, uhi),				\
113 		"clamp("#val", "#lo", "#hi") signedness error");		\
114 	__clamp(uval, ulo, uhi); })
115 
116 #define __careful_clamp(val, lo, hi) \
117 	__clamp_once(val, lo, hi, __UNIQUE_ID(v_), __UNIQUE_ID(l_), __UNIQUE_ID(h_))
118 
119 /**
120  * min - return minimum of two values of the same or compatible types
121  * @x: first value
122  * @y: second value
123  */
124 #define min(x, y)	__careful_cmp(min, x, y)
125 
126 /**
127  * max - return maximum of two values of the same or compatible types
128  * @x: first value
129  * @y: second value
130  */
131 #define max(x, y)	__careful_cmp(max, x, y)
132 
133 /**
134  * umin - return minimum of two non-negative values
135  *   Signed types are zero extended to match a larger unsigned type.
136  * @x: first value
137  * @y: second value
138  */
139 #define umin(x, y)	\
140 	__careful_cmp(min, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
141 
142 /**
143  * umax - return maximum of two non-negative values
144  * @x: first value
145  * @y: second value
146  */
147 #define umax(x, y)	\
148 	__careful_cmp(max, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
149 
150 #define __careful_op3(op, x, y, z, ux, uy, uz) ({			\
151 	__auto_type ux = (x); __auto_type uy = (y);__auto_type uz = (z);\
152 	BUILD_BUG_ON_MSG(!__types_ok3(ux, uy, uz),			\
153 		#op"3("#x", "#y", "#z") signedness error");		\
154 	__cmp(op, ux, __cmp(op, uy, uz)); })
155 
156 /**
157  * min3 - return minimum of three values
158  * @x: first value
159  * @y: second value
160  * @z: third value
161  */
162 #define min3(x, y, z) \
163 	__careful_op3(min, x, y, z, __UNIQUE_ID(x_), __UNIQUE_ID(y_), __UNIQUE_ID(z_))
164 
165 /**
166  * max3 - return maximum of three values
167  * @x: first value
168  * @y: second value
169  * @z: third value
170  */
171 #define max3(x, y, z) \
172 	__careful_op3(max, x, y, z, __UNIQUE_ID(x_), __UNIQUE_ID(y_), __UNIQUE_ID(z_))
173 
174 /**
175  * min_not_zero - return the minimum that is _not_ zero, unless both are zero
176  * @x: value1
177  * @y: value2
178  */
179 #define min_not_zero(x, y) ({			\
180 	typeof(x) __x = (x);			\
181 	typeof(y) __y = (y);			\
182 	__x == 0 ? __y : ((__y == 0) ? __x : min(__x, __y)); })
183 
184 /**
185  * clamp - return a value clamped to a given range with strict typechecking
186  * @val: current value
187  * @lo: lowest allowable value
188  * @hi: highest allowable value
189  *
190  * This macro does strict typechecking of @lo/@hi to make sure they are of the
191  * same type as @val.  See the unnecessary pointer comparisons.
192  */
193 #define clamp(val, lo, hi) __careful_clamp(val, lo, hi)
194 
195 /*
196  * ..and if you can't take the strict
197  * types, you can specify one yourself.
198  *
199  * Or not use min/max/clamp at all, of course.
200  */
201 
202 /**
203  * min_t - return minimum of two values, using the specified type
204  * @type: data type to use
205  * @x: first value
206  * @y: second value
207  */
208 #define min_t(type, x, y) __cmp_once(min, type, x, y)
209 
210 /**
211  * max_t - return maximum of two values, using the specified type
212  * @type: data type to use
213  * @x: first value
214  * @y: second value
215  */
216 #define max_t(type, x, y) __cmp_once(max, type, x, y)
217 
218 /*
219  * Do not check the array parameter using __must_be_array().
220  * In the following legit use-case where the "array" passed is a simple pointer,
221  * __must_be_array() will return a failure.
222  * --- 8< ---
223  * int *buff
224  * ...
225  * min = min_array(buff, nb_items);
226  * --- 8< ---
227  *
228  * The first typeof(&(array)[0]) is needed in order to support arrays of both
229  * 'int *buff' and 'int buff[N]' types.
230  *
231  * The array can be an array of const items.
232  * typeof() keeps the const qualifier. Use __unqual_scalar_typeof() in order
233  * to discard the const qualifier for the __element variable.
234  */
235 #define __minmax_array(op, array, len) ({				\
236 	typeof(&(array)[0]) __array = (array);				\
237 	typeof(len) __len = (len);					\
238 	__unqual_scalar_typeof(__array[0]) __element = __array[--__len];\
239 	while (__len--)							\
240 		__element = op(__element, __array[__len]);		\
241 	__element; })
242 
243 /**
244  * min_array - return minimum of values present in an array
245  * @array: array
246  * @len: array length
247  *
248  * Note that @len must not be zero (empty array).
249  */
250 #define min_array(array, len) __minmax_array(min, array, len)
251 
252 /**
253  * max_array - return maximum of values present in an array
254  * @array: array
255  * @len: array length
256  *
257  * Note that @len must not be zero (empty array).
258  */
259 #define max_array(array, len) __minmax_array(max, array, len)
260 
261 /**
262  * clamp_t - return a value clamped to a given range using a given type
263  * @type: the type of variable to use
264  * @val: current value
265  * @lo: minimum allowable value
266  * @hi: maximum allowable value
267  *
268  * This macro does no typechecking and uses temporary variables of type
269  * @type to make all the comparisons.
270  */
271 #define clamp_t(type, val, lo, hi) __careful_clamp((type)(val), (type)(lo), (type)(hi))
272 
273 /**
274  * clamp_val - return a value clamped to a given range using val's type
275  * @val: current value
276  * @lo: minimum allowable value
277  * @hi: maximum allowable value
278  *
279  * This macro does no typechecking and uses temporary variables of whatever
280  * type the input argument @val is.  This is useful when @val is an unsigned
281  * type and @lo and @hi are literals that will otherwise be assigned a signed
282  * integer type.
283  */
284 #define clamp_val(val, lo, hi) clamp_t(typeof(val), val, lo, hi)
285 
286 static inline bool in_range64(u64 val, u64 start, u64 len)
287 {
288 	return (val - start) < len;
289 }
290 
291 static inline bool in_range32(u32 val, u32 start, u32 len)
292 {
293 	return (val - start) < len;
294 }
295 
296 /**
297  * in_range - Determine if a value lies within a range.
298  * @val: Value to test.
299  * @start: First value in range.
300  * @len: Number of values in range.
301  *
302  * This is more efficient than "if (start <= val && val < (start + len))".
303  * It also gives a different answer if @start + @len overflows the size of
304  * the type by a sufficient amount to encompass @val.  Decide for yourself
305  * which behaviour you want, or prove that start + len never overflow.
306  * Do not blindly replace one form with the other.
307  */
308 #define in_range(val, start, len)					\
309 	((sizeof(start) | sizeof(len) | sizeof(val)) <= sizeof(u32) ?	\
310 		in_range32(val, start, len) : in_range64(val, start, len))
311 
312 /**
313  * swap - swap values of @a and @b
314  * @a: first value
315  * @b: second value
316  */
317 #define swap(a, b) \
318 	do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
319 
320 /*
321  * Use these carefully: no type checking, and uses the arguments
322  * multiple times. Use for obvious constants only.
323  */
324 #define MIN(a, b) __cmp(min, a, b)
325 #define MAX(a, b) __cmp(max, a, b)
326 #define MIN_T(type, a, b) __cmp(min, (type)(a), (type)(b))
327 #define MAX_T(type, a, b) __cmp(max, (type)(a), (type)(b))
328 
329 #endif	/* _LINUX_MINMAX_H */
330