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 __sign_use(ux) (is_signed_type(typeof(ux)) ? \
50 (2 + __is_nonneg(ux)) : (1 + 2 * (sizeof(ux) < 4)))
51
52 /*
53 * Check whether a signed value is always non-negative.
54 *
55 * A cast is needed to avoid any warnings from values that aren't signed
56 * integer types (in which case the result doesn't matter).
57 *
58 * On 64-bit any integer or pointer type can safely be cast to 'long long'.
59 * But on 32-bit we need to avoid warnings about casting pointers to integers
60 * of different sizes without truncating 64-bit values so 'long' or 'long long'
61 * must be used depending on the size of the value.
62 *
63 * This does not work for 128-bit signed integers since the cast would truncate
64 * them, but we do not use s128 types in the kernel (we do use 'u128',
65 * but they are handled by the !is_signed_type() case).
66 */
67 #if __SIZEOF_POINTER__ == __SIZEOF_LONG_LONG__
68 #define __is_nonneg(ux) statically_true((long long)(ux) >= 0)
69 #else
70 #define __is_nonneg(ux) statically_true( \
71 (typeof(__builtin_choose_expr(sizeof(ux) > 4, 1LL, 1L)))(ux) >= 0)
72 #endif
73
74 #define __types_ok(ux, uy) \
75 (__sign_use(ux) & __sign_use(uy))
76
77 #define __types_ok3(ux, uy, uz) \
78 (__sign_use(ux) & __sign_use(uy) & __sign_use(uz))
79
80 #define __cmp_op_min <
81 #define __cmp_op_max >
82
83 #define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (x) : (y))
84
85 #define __cmp_once_unique(op, type, x, y, ux, uy) \
86 ({ type ux = (x); type uy = (y); __cmp(op, ux, uy); })
87
88 #define __cmp_once(op, type, x, y) \
89 __cmp_once_unique(op, type, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
90
91 #define __careful_cmp_once(op, x, y, ux, uy) ({ \
92 __auto_type ux = (x); __auto_type uy = (y); \
93 BUILD_BUG_ON_MSG(!__types_ok(ux, uy), \
94 #op"("#x", "#y") signedness error"); \
95 __cmp(op, ux, uy); })
96
97 #define __careful_cmp(op, x, y) \
98 __careful_cmp_once(op, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
99
100 /**
101 * min - return minimum of two values of the same or compatible types
102 * @x: first value
103 * @y: second value
104 */
105 #define min(x, y) __careful_cmp(min, x, y)
106
107 /**
108 * max - return maximum of two values of the same or compatible types
109 * @x: first value
110 * @y: second value
111 */
112 #define max(x, y) __careful_cmp(max, x, y)
113
114 /**
115 * umin - return minimum of two non-negative values
116 * Signed types are zero extended to match a larger unsigned type.
117 * @x: first value
118 * @y: second value
119 */
120 #define umin(x, y) \
121 __careful_cmp(min, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
122
123 /**
124 * umax - return maximum of two non-negative values
125 * @x: first value
126 * @y: second value
127 */
128 #define umax(x, y) \
129 __careful_cmp(max, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
130
131 #define __careful_op3(op, x, y, z, ux, uy, uz) ({ \
132 __auto_type ux = (x); __auto_type uy = (y);__auto_type uz = (z);\
133 BUILD_BUG_ON_MSG(!__types_ok3(ux, uy, uz), \
134 #op"3("#x", "#y", "#z") signedness error"); \
135 __cmp(op, ux, __cmp(op, uy, uz)); })
136
137 /**
138 * min3 - return minimum of three values
139 * @x: first value
140 * @y: second value
141 * @z: third value
142 */
143 #define min3(x, y, z) \
144 __careful_op3(min, x, y, z, __UNIQUE_ID(x_), __UNIQUE_ID(y_), __UNIQUE_ID(z_))
145
146 /**
147 * max3 - return maximum of three values
148 * @x: first value
149 * @y: second value
150 * @z: third value
151 */
152 #define max3(x, y, z) \
153 __careful_op3(max, x, y, z, __UNIQUE_ID(x_), __UNIQUE_ID(y_), __UNIQUE_ID(z_))
154
155 /**
156 * min_t - return minimum of two values, using the specified type
157 * @type: data type to use
158 * @x: first value
159 * @y: second value
160 */
161 #define min_t(type, x, y) __cmp_once(min, type, x, y)
162
163 /**
164 * max_t - return maximum of two values, using the specified type
165 * @type: data type to use
166 * @x: first value
167 * @y: second value
168 */
169 #define max_t(type, x, y) __cmp_once(max, type, x, y)
170
171 /**
172 * min_not_zero - return the minimum that is _not_ zero, unless both are zero
173 * @x: value1
174 * @y: value2
175 */
176 #define min_not_zero(x, y) ({ \
177 typeof(x) __x = (x); \
178 typeof(y) __y = (y); \
179 __x == 0 ? __y : ((__y == 0) ? __x : min(__x, __y)); })
180
181 #define __clamp(val, lo, hi) \
182 ((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
183
184 #define __clamp_once(type, val, lo, hi, uval, ulo, uhi) ({ \
185 type uval = (val); \
186 type ulo = (lo); \
187 type uhi = (hi); \
188 BUILD_BUG_ON_MSG(statically_true(ulo > uhi), \
189 "clamp() low limit " #lo " greater than high limit " #hi); \
190 BUILD_BUG_ON_MSG(!__types_ok3(uval, ulo, uhi), \
191 "clamp("#val", "#lo", "#hi") signedness error"); \
192 __clamp(uval, ulo, uhi); })
193
194 #define __careful_clamp(type, val, lo, hi) \
195 __clamp_once(type, val, lo, hi, __UNIQUE_ID(v_), __UNIQUE_ID(l_), __UNIQUE_ID(h_))
196
197 /**
198 * clamp - return a value clamped to a given range with typechecking
199 * @val: current value
200 * @lo: lowest allowable value
201 * @hi: highest allowable value
202 *
203 * This macro checks @val/@lo/@hi to make sure they have compatible
204 * signedness.
205 */
206 #define clamp(val, lo, hi) __careful_clamp(__auto_type, val, lo, hi)
207
208 /**
209 * clamp_t - return a value clamped to a given range using a given type
210 * @type: the type of variable to use
211 * @val: current value
212 * @lo: minimum allowable value
213 * @hi: maximum allowable value
214 *
215 * This macro does no typechecking and uses temporary variables of type
216 * @type to make all the comparisons.
217 */
218 #define clamp_t(type, val, lo, hi) __careful_clamp(type, val, lo, hi)
219
220 /**
221 * clamp_val - return a value clamped to a given range using val's type
222 * @val: current value
223 * @lo: minimum allowable value
224 * @hi: maximum allowable value
225 *
226 * This macro does no typechecking and uses temporary variables of whatever
227 * type the input argument @val is. This is useful when @val is an unsigned
228 * type and @lo and @hi are literals that will otherwise be assigned a signed
229 * integer type.
230 */
231 #define clamp_val(val, lo, hi) __careful_clamp(typeof(val), val, lo, hi)
232
233 /*
234 * Do not check the array parameter using __must_be_array().
235 * In the following legit use-case where the "array" passed is a simple pointer,
236 * __must_be_array() will return a failure.
237 * --- 8< ---
238 * int *buff
239 * ...
240 * min = min_array(buff, nb_items);
241 * --- 8< ---
242 *
243 * The first typeof(&(array)[0]) is needed in order to support arrays of both
244 * 'int *buff' and 'int buff[N]' types.
245 *
246 * The array can be an array of const items.
247 * typeof() keeps the const qualifier. Use __unqual_scalar_typeof() in order
248 * to discard the const qualifier for the __element variable.
249 */
250 #define __minmax_array(op, array, len) ({ \
251 typeof(&(array)[0]) __array = (array); \
252 typeof(len) __len = (len); \
253 __unqual_scalar_typeof(__array[0]) __element = __array[--__len];\
254 while (__len--) \
255 __element = op(__element, __array[__len]); \
256 __element; })
257
258 /**
259 * min_array - return minimum of values present in an array
260 * @array: array
261 * @len: array length
262 *
263 * Note that @len must not be zero (empty array).
264 */
265 #define min_array(array, len) __minmax_array(min, array, len)
266
267 /**
268 * max_array - return maximum of values present in an array
269 * @array: array
270 * @len: array length
271 *
272 * Note that @len must not be zero (empty array).
273 */
274 #define max_array(array, len) __minmax_array(max, array, len)
275
in_range64(u64 val,u64 start,u64 len)276 static inline bool in_range64(u64 val, u64 start, u64 len)
277 {
278 return (val - start) < len;
279 }
280
in_range32(u32 val,u32 start,u32 len)281 static inline bool in_range32(u32 val, u32 start, u32 len)
282 {
283 return (val - start) < len;
284 }
285
286 /**
287 * in_range - Determine if a value lies within a range.
288 * @val: Value to test.
289 * @start: First value in range.
290 * @len: Number of values in range.
291 *
292 * This is more efficient than "if (start <= val && val < (start + len))".
293 * It also gives a different answer if @start + @len overflows the size of
294 * the type by a sufficient amount to encompass @val. Decide for yourself
295 * which behaviour you want, or prove that start + len never overflow.
296 * Do not blindly replace one form with the other.
297 */
298 #define in_range(val, start, len) \
299 ((sizeof(start) | sizeof(len) | sizeof(val)) <= sizeof(u32) ? \
300 in_range32(val, start, len) : in_range64(val, start, len))
301
302 /**
303 * swap - swap values of @a and @b
304 * @a: first value
305 * @b: second value
306 */
307 #define swap(a, b) \
308 do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
309
310 /*
311 * Use these carefully: no type checking, and uses the arguments
312 * multiple times. Use for obvious constants only.
313 */
314 #define MIN(a, b) __cmp(min, a, b)
315 #define MAX(a, b) __cmp(max, a, b)
316 #define MIN_T(type, a, b) __cmp(min, (type)(a), (type)(b))
317 #define MAX_T(type, a, b) __cmp(max, (type)(a), (type)(b))
318
319 #endif /* _LINUX_MINMAX_H */
320