xref: /linux-6.15/include/linux/minmax.h (revision 2b97aaf7)
1b296a6d5SAndy Shevchenko /* SPDX-License-Identifier: GPL-2.0 */
2b296a6d5SAndy Shevchenko #ifndef _LINUX_MINMAX_H
3b296a6d5SAndy Shevchenko #define _LINUX_MINMAX_H
4b296a6d5SAndy Shevchenko 
5f6e9d38fSAndy Shevchenko #include <linux/build_bug.h>
6f6e9d38fSAndy Shevchenko #include <linux/compiler.h>
7f747e666SRikard Falkeborn #include <linux/const.h>
8f9bff0e3SMatthew Wilcox (Oracle) #include <linux/types.h>
9f747e666SRikard Falkeborn 
10b296a6d5SAndy Shevchenko /*
1110666e99SDavid Laight  * min()/max()/clamp() macros must accomplish several things:
12b296a6d5SAndy Shevchenko  *
13867046ccSDavid Laight  * - Avoid multiple evaluations of the arguments (so side-effects like
14b296a6d5SAndy Shevchenko  *   "x++" happen only once) when non-constant.
15867046ccSDavid Laight  * - Perform signed v unsigned type-checking (to generate compile
16867046ccSDavid Laight  *   errors instead of nasty runtime surprises).
17867046ccSDavid Laight  * - Unsigned char/short are always promoted to signed int and can be
18867046ccSDavid Laight  *   compared against signed or unsigned arguments.
19867046ccSDavid Laight  * - Unsigned arguments can be compared against non-negative signed constants.
20867046ccSDavid Laight  * - Comparison of a signed argument against an unsigned constant fails
21867046ccSDavid Laight  *   even if the constant is below __INT_MAX__ and could be cast to int.
22b296a6d5SAndy Shevchenko  */
23b296a6d5SAndy Shevchenko #define __typecheck(x, y) \
24b296a6d5SAndy Shevchenko 	(!!(sizeof((typeof(x) *)1 == (typeof(y) *)1)))
25b296a6d5SAndy Shevchenko 
2622f54687SLinus Torvalds /*
2722f54687SLinus Torvalds  * __sign_use for integer expressions:
2822f54687SLinus Torvalds  *   bit #0 set if ok for unsigned comparisons
2922f54687SLinus Torvalds  *   bit #1 set if ok for signed comparisons
3022f54687SLinus Torvalds  *
3110666e99SDavid Laight  * In particular, statically non-negative signed integer expressions
3210666e99SDavid Laight  * are ok for both.
3322f54687SLinus Torvalds  *
3410666e99SDavid Laight  * NOTE! Unsigned types smaller than 'int' are implicitly converted to 'int'
3510666e99SDavid Laight  * in expressions, and are accepted for signed conversions for now.
3610666e99SDavid Laight  * This is debatable.
3722f54687SLinus Torvalds  *
3810666e99SDavid Laight  * Note that 'x' is the original expression, and 'ux' is the unique variable
3910666e99SDavid Laight  * that contains the value.
4022f54687SLinus Torvalds  *
4110666e99SDavid Laight  * We use 'ux' for pure type checking, and 'x' for when we need to look at the
4210666e99SDavid Laight  * value (but without evaluating it for side effects!
4310666e99SDavid Laight  * Careful to only ever evaluate it with sizeof() or __builtin_constant_p() etc).
4422f54687SLinus Torvalds  *
4510666e99SDavid Laight  * Pointers end up being checked by the normal C type rules at the actual
4610666e99SDavid Laight  * comparison, and these expressions only need to be careful to not cause
4710666e99SDavid Laight  * warnings for pointer use.
4822f54687SLinus Torvalds  */
49b280bb27SDavid Laight #define __sign_use(ux) (is_signed_type(typeof(ux)) ? \
50*2b97aaf7SDavid Laight 	(2 + __is_nonneg(ux)) : (1 + 2 * (sizeof(ux) < 4)))
51b296a6d5SAndy Shevchenko 
5222f54687SLinus Torvalds /*
5310666e99SDavid Laight  * Check whether a signed value is always non-negative.
5422f54687SLinus Torvalds  *
5510666e99SDavid Laight  * A cast is needed to avoid any warnings from values that aren't signed
5610666e99SDavid Laight  * integer types (in which case the result doesn't matter).
5722f54687SLinus Torvalds  *
58*2b97aaf7SDavid Laight  * On 64-bit any integer or pointer type can safely be cast to 'long long'.
5910666e99SDavid Laight  * But on 32-bit we need to avoid warnings about casting pointers to integers
6010666e99SDavid Laight  * of different sizes without truncating 64-bit values so 'long' or 'long long'
6110666e99SDavid Laight  * must be used depending on the size of the value.
6222f54687SLinus Torvalds  *
6310666e99SDavid Laight  * This does not work for 128-bit signed integers since the cast would truncate
6410666e99SDavid Laight  * them, but we do not use s128 types in the kernel (we do use 'u128',
6510666e99SDavid Laight  * but they are handled by the !is_signed_type() case).
6622f54687SLinus Torvalds  */
67*2b97aaf7SDavid Laight #if __SIZEOF_POINTER__ == __SIZEOF_LONG_LONG__
68*2b97aaf7SDavid Laight #define __is_nonneg(ux) statically_true((long long)(ux) >= 0)
6922f54687SLinus Torvalds #else
70*2b97aaf7SDavid Laight #define __is_nonneg(ux) statically_true( \
71*2b97aaf7SDavid Laight 	(typeof(__builtin_choose_expr(sizeof(ux) > 4, 1LL, 1L)))(ux) >= 0)
7222f54687SLinus Torvalds #endif
73867046ccSDavid Laight 
74b280bb27SDavid Laight #define __types_ok(ux, uy) \
75b280bb27SDavid Laight 	(__sign_use(ux) & __sign_use(uy))
7622f54687SLinus Torvalds 
77b280bb27SDavid Laight #define __types_ok3(ux, uy, uz) \
78b280bb27SDavid Laight 	(__sign_use(ux) & __sign_use(uy) & __sign_use(uz))
79b296a6d5SAndy Shevchenko 
80d03eba99SDavid Laight #define __cmp_op_min <
81d03eba99SDavid Laight #define __cmp_op_max >
82b296a6d5SAndy Shevchenko 
83d03eba99SDavid Laight #define __cmp(op, x, y)	((x) __cmp_op_##op (y) ? (x) : (y))
84d03eba99SDavid Laight 
85017fa3e8SLinus Torvalds #define __cmp_once_unique(op, type, x, y, ux, uy) \
86017fa3e8SLinus Torvalds 	({ type ux = (x); type uy = (y); __cmp(op, ux, uy); })
87017fa3e8SLinus Torvalds 
88017fa3e8SLinus Torvalds #define __cmp_once(op, type, x, y) \
89017fa3e8SLinus Torvalds 	__cmp_once_unique(op, type, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
90017fa3e8SLinus Torvalds 
91dc1c8034SLinus Torvalds #define __careful_cmp_once(op, x, y, ux, uy) ({		\
92dc1c8034SLinus Torvalds 	__auto_type ux = (x); __auto_type uy = (y);	\
93b280bb27SDavid Laight 	BUILD_BUG_ON_MSG(!__types_ok(ux, uy),		\
9422f54687SLinus Torvalds 		#op"("#x", "#y") signedness error");	\
95dc1c8034SLinus Torvalds 	__cmp(op, ux, uy); })
96b296a6d5SAndy Shevchenko 
97d03eba99SDavid Laight #define __careful_cmp(op, x, y) \
98dc1c8034SLinus Torvalds 	__careful_cmp_once(op, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
99b296a6d5SAndy Shevchenko 
100b296a6d5SAndy Shevchenko /**
101b296a6d5SAndy Shevchenko  * min - return minimum of two values of the same or compatible types
102b296a6d5SAndy Shevchenko  * @x: first value
103b296a6d5SAndy Shevchenko  * @y: second value
104b296a6d5SAndy Shevchenko  */
105d03eba99SDavid Laight #define min(x, y)	__careful_cmp(min, x, y)
106b296a6d5SAndy Shevchenko 
107b296a6d5SAndy Shevchenko /**
108b296a6d5SAndy Shevchenko  * max - return maximum of two values of the same or compatible types
109b296a6d5SAndy Shevchenko  * @x: first value
110b296a6d5SAndy Shevchenko  * @y: second value
111b296a6d5SAndy Shevchenko  */
112d03eba99SDavid Laight #define max(x, y)	__careful_cmp(max, x, y)
113b296a6d5SAndy Shevchenko 
114b296a6d5SAndy Shevchenko /**
11580fcac55SDavid Laight  * umin - return minimum of two non-negative values
11680fcac55SDavid Laight  *   Signed types are zero extended to match a larger unsigned type.
11780fcac55SDavid Laight  * @x: first value
11880fcac55SDavid Laight  * @y: second value
11980fcac55SDavid Laight  */
12080fcac55SDavid Laight #define umin(x, y)	\
121d03eba99SDavid Laight 	__careful_cmp(min, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
12280fcac55SDavid Laight 
12380fcac55SDavid Laight /**
12480fcac55SDavid Laight  * umax - return maximum of two non-negative values
12580fcac55SDavid Laight  * @x: first value
12680fcac55SDavid Laight  * @y: second value
12780fcac55SDavid Laight  */
12880fcac55SDavid Laight #define umax(x, y)	\
129d03eba99SDavid Laight 	__careful_cmp(max, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
13080fcac55SDavid Laight 
13121b136ccSLinus Torvalds #define __careful_op3(op, x, y, z, ux, uy, uz) ({			\
13221b136ccSLinus Torvalds 	__auto_type ux = (x); __auto_type uy = (y);__auto_type uz = (z);\
133b280bb27SDavid Laight 	BUILD_BUG_ON_MSG(!__types_ok3(ux, uy, uz),			\
13421b136ccSLinus Torvalds 		#op"3("#x", "#y", "#z") signedness error");		\
13521b136ccSLinus Torvalds 	__cmp(op, ux, __cmp(op, uy, uz)); })
13621b136ccSLinus Torvalds 
13780fcac55SDavid Laight /**
138b296a6d5SAndy Shevchenko  * min3 - return minimum of three values
139b296a6d5SAndy Shevchenko  * @x: first value
140b296a6d5SAndy Shevchenko  * @y: second value
141b296a6d5SAndy Shevchenko  * @z: third value
142b296a6d5SAndy Shevchenko  */
14321b136ccSLinus Torvalds #define min3(x, y, z) \
14421b136ccSLinus Torvalds 	__careful_op3(min, x, y, z, __UNIQUE_ID(x_), __UNIQUE_ID(y_), __UNIQUE_ID(z_))
145b296a6d5SAndy Shevchenko 
146b296a6d5SAndy Shevchenko /**
147b296a6d5SAndy Shevchenko  * max3 - return maximum of three values
148b296a6d5SAndy Shevchenko  * @x: first value
149b296a6d5SAndy Shevchenko  * @y: second value
150b296a6d5SAndy Shevchenko  * @z: third value
151b296a6d5SAndy Shevchenko  */
15221b136ccSLinus Torvalds #define max3(x, y, z) \
15321b136ccSLinus Torvalds 	__careful_op3(max, x, y, z, __UNIQUE_ID(x_), __UNIQUE_ID(y_), __UNIQUE_ID(z_))
154b296a6d5SAndy Shevchenko 
155b296a6d5SAndy Shevchenko /**
156b296a6d5SAndy Shevchenko  * min_t - return minimum of two values, using the specified type
157b296a6d5SAndy Shevchenko  * @type: data type to use
158b296a6d5SAndy Shevchenko  * @x: first value
159b296a6d5SAndy Shevchenko  * @y: second value
160b296a6d5SAndy Shevchenko  */
161017fa3e8SLinus Torvalds #define min_t(type, x, y) __cmp_once(min, type, x, y)
162b296a6d5SAndy Shevchenko 
163b296a6d5SAndy Shevchenko /**
164b296a6d5SAndy Shevchenko  * max_t - return maximum of two values, using the specified type
165b296a6d5SAndy Shevchenko  * @type: data type to use
166b296a6d5SAndy Shevchenko  * @x: first value
167b296a6d5SAndy Shevchenko  * @y: second value
168b296a6d5SAndy Shevchenko  */
169017fa3e8SLinus Torvalds #define max_t(type, x, y) __cmp_once(max, type, x, y)
170b296a6d5SAndy Shevchenko 
171c3939872SDavid Laight /**
172c3939872SDavid Laight  * min_not_zero - return the minimum that is _not_ zero, unless both are zero
173c3939872SDavid Laight  * @x: value1
174c3939872SDavid Laight  * @y: value2
175c3939872SDavid Laight  */
176c3939872SDavid Laight #define min_not_zero(x, y) ({			\
177c3939872SDavid Laight 	typeof(x) __x = (x);			\
178c3939872SDavid Laight 	typeof(y) __y = (y);			\
179c3939872SDavid Laight 	__x == 0 ? __y : ((__y == 0) ? __x : min(__x, __y)); })
180c3939872SDavid Laight 
181c3939872SDavid Laight #define __clamp(val, lo, hi)	\
182c3939872SDavid Laight 	((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
183c3939872SDavid Laight 
184495bba17SDavid Laight #define __clamp_once(type, val, lo, hi, uval, ulo, uhi) ({			\
185495bba17SDavid Laight 	type uval = (val);							\
186495bba17SDavid Laight 	type ulo = (lo);							\
187495bba17SDavid Laight 	type uhi = (hi);							\
188c3939872SDavid Laight 	BUILD_BUG_ON_MSG(statically_true(ulo > uhi),				\
189c3939872SDavid Laight 		"clamp() low limit " #lo " greater than high limit " #hi);	\
190c3939872SDavid Laight 	BUILD_BUG_ON_MSG(!__types_ok3(uval, ulo, uhi),				\
191c3939872SDavid Laight 		"clamp("#val", "#lo", "#hi") signedness error");		\
192c3939872SDavid Laight 	__clamp(uval, ulo, uhi); })
193c3939872SDavid Laight 
194495bba17SDavid Laight #define __careful_clamp(type, val, lo, hi) \
195495bba17SDavid Laight 	__clamp_once(type, val, lo, hi, __UNIQUE_ID(v_), __UNIQUE_ID(l_), __UNIQUE_ID(h_))
196c3939872SDavid Laight 
197c3939872SDavid Laight /**
198495bba17SDavid Laight  * clamp - return a value clamped to a given range with typechecking
199c3939872SDavid Laight  * @val: current value
200c3939872SDavid Laight  * @lo: lowest allowable value
201c3939872SDavid Laight  * @hi: highest allowable value
202c3939872SDavid Laight  *
203495bba17SDavid Laight  * This macro checks @val/@lo/@hi to make sure they have compatible
204495bba17SDavid Laight  * signedness.
205c3939872SDavid Laight  */
206495bba17SDavid Laight #define clamp(val, lo, hi) __careful_clamp(__auto_type, val, lo, hi)
207c3939872SDavid Laight 
208c3939872SDavid Laight /**
209c3939872SDavid Laight  * clamp_t - return a value clamped to a given range using a given type
210c3939872SDavid Laight  * @type: the type of variable to use
211c3939872SDavid Laight  * @val: current value
212c3939872SDavid Laight  * @lo: minimum allowable value
213c3939872SDavid Laight  * @hi: maximum allowable value
214c3939872SDavid Laight  *
215c3939872SDavid Laight  * This macro does no typechecking and uses temporary variables of type
216c3939872SDavid Laight  * @type to make all the comparisons.
217c3939872SDavid Laight  */
218495bba17SDavid Laight #define clamp_t(type, val, lo, hi) __careful_clamp(type, val, lo, hi)
219c3939872SDavid Laight 
220c3939872SDavid Laight /**
221c3939872SDavid Laight  * clamp_val - return a value clamped to a given range using val's type
222c3939872SDavid Laight  * @val: current value
223c3939872SDavid Laight  * @lo: minimum allowable value
224c3939872SDavid Laight  * @hi: maximum allowable value
225c3939872SDavid Laight  *
226c3939872SDavid Laight  * This macro does no typechecking and uses temporary variables of whatever
227c3939872SDavid Laight  * type the input argument @val is.  This is useful when @val is an unsigned
228c3939872SDavid Laight  * type and @lo and @hi are literals that will otherwise be assigned a signed
229c3939872SDavid Laight  * integer type.
230c3939872SDavid Laight  */
231495bba17SDavid Laight #define clamp_val(val, lo, hi) __careful_clamp(typeof(val), val, lo, hi)
232c3939872SDavid Laight 
233c952c748SHerve Codina /*
234c952c748SHerve Codina  * Do not check the array parameter using __must_be_array().
235c952c748SHerve Codina  * In the following legit use-case where the "array" passed is a simple pointer,
236c952c748SHerve Codina  * __must_be_array() will return a failure.
237c952c748SHerve Codina  * --- 8< ---
238c952c748SHerve Codina  * int *buff
239c952c748SHerve Codina  * ...
240c952c748SHerve Codina  * min = min_array(buff, nb_items);
241c952c748SHerve Codina  * --- 8< ---
242c952c748SHerve Codina  *
243c952c748SHerve Codina  * The first typeof(&(array)[0]) is needed in order to support arrays of both
244c952c748SHerve Codina  * 'int *buff' and 'int buff[N]' types.
245c952c748SHerve Codina  *
246c952c748SHerve Codina  * The array can be an array of const items.
2475e57418aSAndy Shevchenko  * typeof() keeps the const qualifier. Use __unqual_scalar_typeof() in order
248c952c748SHerve Codina  * to discard the const qualifier for the __element variable.
249c952c748SHerve Codina  */
250c952c748SHerve Codina #define __minmax_array(op, array, len) ({				\
251c952c748SHerve Codina 	typeof(&(array)[0]) __array = (array);				\
252c952c748SHerve Codina 	typeof(len) __len = (len);					\
2535e57418aSAndy Shevchenko 	__unqual_scalar_typeof(__array[0]) __element = __array[--__len];\
254c952c748SHerve Codina 	while (__len--)							\
255c952c748SHerve Codina 		__element = op(__element, __array[__len]);		\
256c952c748SHerve Codina 	__element; })
257c952c748SHerve Codina 
258c952c748SHerve Codina /**
259c952c748SHerve Codina  * min_array - return minimum of values present in an array
260c952c748SHerve Codina  * @array: array
261c952c748SHerve Codina  * @len: array length
262c952c748SHerve Codina  *
263c952c748SHerve Codina  * Note that @len must not be zero (empty array).
264c952c748SHerve Codina  */
265c952c748SHerve Codina #define min_array(array, len) __minmax_array(min, array, len)
266c952c748SHerve Codina 
267c952c748SHerve Codina /**
268c952c748SHerve Codina  * max_array - return maximum of values present in an array
269c952c748SHerve Codina  * @array: array
270c952c748SHerve Codina  * @len: array length
271c952c748SHerve Codina  *
272c952c748SHerve Codina  * Note that @len must not be zero (empty array).
273c952c748SHerve Codina  */
274c952c748SHerve Codina #define max_array(array, len) __minmax_array(max, array, len)
275c952c748SHerve Codina 
in_range64(u64 val,u64 start,u64 len)276f9bff0e3SMatthew Wilcox (Oracle) static inline bool in_range64(u64 val, u64 start, u64 len)
277f9bff0e3SMatthew Wilcox (Oracle) {
278f9bff0e3SMatthew Wilcox (Oracle) 	return (val - start) < len;
279f9bff0e3SMatthew Wilcox (Oracle) }
280f9bff0e3SMatthew Wilcox (Oracle) 
in_range32(u32 val,u32 start,u32 len)281f9bff0e3SMatthew Wilcox (Oracle) static inline bool in_range32(u32 val, u32 start, u32 len)
282f9bff0e3SMatthew Wilcox (Oracle) {
283f9bff0e3SMatthew Wilcox (Oracle) 	return (val - start) < len;
284f9bff0e3SMatthew Wilcox (Oracle) }
285f9bff0e3SMatthew Wilcox (Oracle) 
286f9bff0e3SMatthew Wilcox (Oracle) /**
287f9bff0e3SMatthew Wilcox (Oracle)  * in_range - Determine if a value lies within a range.
288f9bff0e3SMatthew Wilcox (Oracle)  * @val: Value to test.
289f9bff0e3SMatthew Wilcox (Oracle)  * @start: First value in range.
290f9bff0e3SMatthew Wilcox (Oracle)  * @len: Number of values in range.
291f9bff0e3SMatthew Wilcox (Oracle)  *
292f9bff0e3SMatthew Wilcox (Oracle)  * This is more efficient than "if (start <= val && val < (start + len))".
293f9bff0e3SMatthew Wilcox (Oracle)  * It also gives a different answer if @start + @len overflows the size of
294f9bff0e3SMatthew Wilcox (Oracle)  * the type by a sufficient amount to encompass @val.  Decide for yourself
295f9bff0e3SMatthew Wilcox (Oracle)  * which behaviour you want, or prove that start + len never overflow.
296f9bff0e3SMatthew Wilcox (Oracle)  * Do not blindly replace one form with the other.
297f9bff0e3SMatthew Wilcox (Oracle)  */
298f9bff0e3SMatthew Wilcox (Oracle) #define in_range(val, start, len)					\
299f9bff0e3SMatthew Wilcox (Oracle) 	((sizeof(start) | sizeof(len) | sizeof(val)) <= sizeof(u32) ?	\
300f9bff0e3SMatthew Wilcox (Oracle) 		in_range32(val, start, len) : in_range64(val, start, len))
301f9bff0e3SMatthew Wilcox (Oracle) 
302b296a6d5SAndy Shevchenko /**
303b296a6d5SAndy Shevchenko  * swap - swap values of @a and @b
304b296a6d5SAndy Shevchenko  * @a: first value
305b296a6d5SAndy Shevchenko  * @b: second value
306b296a6d5SAndy Shevchenko  */
307b296a6d5SAndy Shevchenko #define swap(a, b) \
308b296a6d5SAndy Shevchenko 	do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
309b296a6d5SAndy Shevchenko 
3103a7e02c0SLinus Torvalds /*
3113a7e02c0SLinus Torvalds  * Use these carefully: no type checking, and uses the arguments
3123a7e02c0SLinus Torvalds  * multiple times. Use for obvious constants only.
3133a7e02c0SLinus Torvalds  */
3141a251f52SLinus Torvalds #define MIN(a, b) __cmp(min, a, b)
3151a251f52SLinus Torvalds #define MAX(a, b) __cmp(max, a, b)
3163a7e02c0SLinus Torvalds #define MIN_T(type, a, b) __cmp(min, (type)(a), (type)(b))
3173a7e02c0SLinus Torvalds #define MAX_T(type, a, b) __cmp(max, (type)(a), (type)(b))
3183a7e02c0SLinus Torvalds 
319b296a6d5SAndy Shevchenko #endif	/* _LINUX_MINMAX_H */
320