Line data Source code
1 1 : /*
2 : * Copyright (c) 2011-2014, Wind River Systems, Inc.
3 : *
4 : * SPDX-License-Identifier: Apache-2.0
5 : */
6 :
7 : /**
8 : * @file
9 : * @brief Misc utilities
10 : *
11 : * Misc utilities usable by the kernel and application code.
12 : */
13 :
14 : #ifndef ZEPHYR_INCLUDE_SYS_UTIL_H_
15 : #define ZEPHYR_INCLUDE_SYS_UTIL_H_
16 :
17 : #include <zephyr/sys/util_macro.h>
18 : #include <zephyr/toolchain.h>
19 :
20 : /* needs to be outside _ASMLANGUAGE so 'true' and 'false' can turn
21 : * into '1' and '0' for asm or linker scripts
22 : */
23 : #include <stdbool.h>
24 :
25 : #ifndef _ASMLANGUAGE
26 :
27 : #include <zephyr/sys/__assert.h>
28 : #include <zephyr/types.h>
29 : #include <stddef.h>
30 : #include <stdint.h>
31 : #include <string.h>
32 :
33 : /** @brief Number of bits that make up a type */
34 1 : #define NUM_BITS(t) (sizeof(t) * BITS_PER_BYTE)
35 :
36 : #ifdef __cplusplus
37 : extern "C" {
38 : #endif
39 :
40 : /**
41 : * @defgroup sys-util Utility Functions
42 : * @since 2.4
43 : * @version 0.1.0
44 : * @ingroup utilities
45 : * @{
46 : */
47 :
48 : /** @brief Cast @p x, a pointer, to an unsigned integer. */
49 1 : #define POINTER_TO_UINT(x) ((uintptr_t)(x))
50 : /** @brief Cast @p x, an unsigned integer, to a <tt>void*</tt>. */
51 1 : #define UINT_TO_POINTER(x) ((void *)(uintptr_t)(x))
52 : /** @brief Cast @p x, a pointer, to a signed integer. */
53 1 : #define POINTER_TO_INT(x) ((intptr_t)(x))
54 : /** @brief Cast @p x, a signed integer, to a <tt>void*</tt>. */
55 1 : #define INT_TO_POINTER(x) ((void *)(intptr_t)(x))
56 :
57 : #if !(defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__) && defined(__SIZEOF_LONG_LONG__))
58 : #error Missing required predefined macros for BITS_PER_LONG calculation
59 : #endif
60 :
61 : /** Number of bits in a byte. */
62 1 : #define BITS_PER_BYTE (__CHAR_BIT__)
63 :
64 : /** Number of bits in a nibble. */
65 1 : #define BITS_PER_NIBBLE (__CHAR_BIT__ / 2)
66 :
67 : /** Number of nibbles in a byte. */
68 1 : #define NIBBLES_PER_BYTE (BITS_PER_BYTE / BITS_PER_NIBBLE)
69 :
70 : /** Number of bits in a long int. */
71 1 : #define BITS_PER_LONG (__CHAR_BIT__ * __SIZEOF_LONG__)
72 :
73 : /** Number of bits in a long long int. */
74 1 : #define BITS_PER_LONG_LONG (__CHAR_BIT__ * __SIZEOF_LONG_LONG__)
75 :
76 : /**
77 : * @brief Create a contiguous bitmask starting at bit position @p l
78 : * and ending at position @p h.
79 : */
80 1 : #define GENMASK(h, l) (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
81 :
82 : /**
83 : * @brief Create a contiguous 64-bit bitmask starting at bit position @p l
84 : * and ending at position @p h.
85 : */
86 1 : #define GENMASK64(h, l) (((~0ULL) - (1ULL << (l)) + 1) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
87 :
88 : /** @brief 0 if @p cond is true-ish; causes a compile error otherwise. */
89 1 : #define ZERO_OR_COMPILE_ERROR(cond) ((int)sizeof(char[1 - (2 * !(cond))]) - 1)
90 :
91 : #if defined(__cplusplus)
92 :
93 : /* The built-in function used below for type checking in C is not
94 : * supported by GNU C++.
95 : */
96 : #define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
97 :
98 : #else /* __cplusplus */
99 :
100 : /**
101 : * @brief Zero if @p array has an array type, a compile error otherwise
102 : *
103 : * This macro is available only from C, not C++.
104 : */
105 1 : #define IS_ARRAY(array) \
106 : ZERO_OR_COMPILE_ERROR( \
107 : !__builtin_types_compatible_p(__typeof__(array), __typeof__(&(array)[0])))
108 :
109 : /**
110 : * @brief Number of elements in the given @p array
111 : *
112 : * In C++, due to language limitations, this will accept as @p array
113 : * any type that implements <tt>operator[]</tt>. The results may not be
114 : * particularly meaningful in this case.
115 : *
116 : * In C, passing a pointer as @p array causes a compile error.
117 : */
118 1 : #define ARRAY_SIZE(array) ((size_t)(IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))
119 :
120 : #endif /* __cplusplus */
121 :
122 : /**
123 : * @brief Declare a flexible array member.
124 : *
125 : * This macro declares a flexible array member in a struct. The member
126 : * is named @p name and has type @p type.
127 : *
128 : * Since C99, flexible arrays are part of the C standard, but for historical
129 : * reasons many places still use an older GNU extension that is declare
130 : * zero length arrays.
131 : *
132 : * Although zero length arrays are flexible arrays, we can't blindly
133 : * replace [0] with [] because of some syntax limitations. This macro
134 : * workaround these limitations.
135 : *
136 : * It is specially useful for cases where flexible arrays are
137 : * used in unions or are not the last element in the struct.
138 : */
139 1 : #define FLEXIBLE_ARRAY_DECLARE(type, name) \
140 : struct { \
141 : struct { \
142 : } __unused_##name; \
143 : type name[]; \
144 : }
145 :
146 : /**
147 : * @brief Whether @p ptr is an element of @p array
148 : *
149 : * This macro can be seen as a slightly stricter version of @ref PART_OF_ARRAY
150 : * in that it also ensures that @p ptr is aligned to an array-element boundary
151 : * of @p array.
152 : *
153 : * In C, passing a pointer as @p array causes a compile error.
154 : *
155 : * @param array the array in question
156 : * @param ptr the pointer to check
157 : *
158 : * @return 1 if @p ptr is part of @p array, 0 otherwise
159 : */
160 1 : #define IS_ARRAY_ELEMENT(array, ptr) \
161 : ((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) && \
162 : POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]) && \
163 : (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) % sizeof((array)[0]) == 0)
164 :
165 : /**
166 : * @brief Index of @p ptr within @p array
167 : *
168 : * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
169 : * when @p ptr does not fall into the range of @p array or when @p ptr
170 : * is not aligned to an array-element boundary of @p array.
171 : *
172 : * In C, passing a pointer as @p array causes a compile error.
173 : *
174 : * @param array the array in question
175 : * @param ptr pointer to an element of @p array
176 : *
177 : * @return the array index of @p ptr within @p array, on success
178 : */
179 1 : #define ARRAY_INDEX(array, ptr) \
180 : ({ \
181 : __ASSERT_NO_MSG(IS_ARRAY_ELEMENT(array, ptr)); \
182 : (__typeof__((array)[0]) *)(ptr) - (array); \
183 : })
184 :
185 : /**
186 : * @brief Check if a pointer @p ptr lies within @p array.
187 : *
188 : * In C but not C++, this causes a compile error if @p array is not an array
189 : * (e.g. if @p ptr and @p array are mixed up).
190 : *
191 : * @param array an array
192 : * @param ptr a pointer
193 : * @return 1 if @p ptr is part of @p array, 0 otherwise
194 : */
195 1 : #define PART_OF_ARRAY(array, ptr) \
196 : ((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) && \
197 : POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]))
198 :
199 : /**
200 : * @brief Array-index of @p ptr within @p array, rounded down
201 : *
202 : * This macro behaves much like @ref ARRAY_INDEX with the notable
203 : * difference that it accepts any @p ptr in the range of @p array rather than
204 : * exclusively a @p ptr aligned to an array-element boundary of @p array.
205 : *
206 : * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
207 : * when @p ptr does not fall into the range of @p array.
208 : *
209 : * In C, passing a pointer as @p array causes a compile error.
210 : *
211 : * @param array the array in question
212 : * @param ptr pointer to an element of @p array
213 : *
214 : * @return the array index of @p ptr within @p array, on success
215 : */
216 1 : #define ARRAY_INDEX_FLOOR(array, ptr) \
217 : ({ \
218 : __ASSERT_NO_MSG(PART_OF_ARRAY(array, ptr)); \
219 : (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) / sizeof((array)[0]); \
220 : })
221 :
222 : /**
223 : * @brief Iterate over members of an array using an index variable
224 : *
225 : * @param array the array in question
226 : * @param idx name of array index variable
227 : */
228 1 : #define ARRAY_FOR_EACH(array, idx) for (size_t idx = 0; (idx) < ARRAY_SIZE(array); ++(idx))
229 :
230 : /**
231 : * @brief Iterate over members of an array using a pointer
232 : *
233 : * @param array the array in question
234 : * @param ptr pointer to an element of @p array
235 : */
236 1 : #define ARRAY_FOR_EACH_PTR(array, ptr) \
237 : for (__typeof__(*(array)) *ptr = (array); (size_t)((ptr) - (array)) < ARRAY_SIZE(array); \
238 : ++(ptr))
239 :
240 : /**
241 : * @brief Validate if two entities have a compatible type
242 : *
243 : * @param a the first entity to be compared
244 : * @param b the second entity to be compared
245 : * @return 1 if the two elements are compatible, 0 if they are not
246 : */
247 1 : #define SAME_TYPE(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
248 :
249 : /**
250 : * @brief Validate CONTAINER_OF parameters, only applies to C mode.
251 : */
252 : #ifndef __cplusplus
253 1 : #define CONTAINER_OF_VALIDATE(ptr, type, field) \
254 : BUILD_ASSERT(SAME_TYPE(*(ptr), ((type *)0)->field) || SAME_TYPE(*(ptr), void), \
255 : "pointer type mismatch in CONTAINER_OF");
256 : #else
257 : #define CONTAINER_OF_VALIDATE(ptr, type, field)
258 : #endif
259 :
260 : /**
261 : * @brief Get a pointer to a structure containing the element
262 : *
263 : * Example:
264 : *
265 : * struct foo {
266 : * int bar;
267 : * };
268 : *
269 : * struct foo my_foo;
270 : * int *ptr = &my_foo.bar;
271 : *
272 : * struct foo *container = CONTAINER_OF(ptr, struct foo, bar);
273 : *
274 : * Above, @p container points at @p my_foo.
275 : *
276 : * @param ptr pointer to a structure element
277 : * @param type name of the type that @p ptr is an element of
278 : * @param field the name of the field within the struct @p ptr points to
279 : * @return a pointer to the structure that contains @p ptr
280 : */
281 1 : #define CONTAINER_OF(ptr, type, field) \
282 : ({ \
283 : CONTAINER_OF_VALIDATE(ptr, type, field) \
284 : ((type *)(((char *)(ptr)) - offsetof(type, field))); \
285 : })
286 :
287 : /**
288 : * @brief Report the size of a struct field in bytes.
289 : *
290 : * @param type The structure containing the field of interest.
291 : * @param member The field to return the size of.
292 : *
293 : * @return The field size.
294 : */
295 1 : #define SIZEOF_FIELD(type, member) sizeof((((type *)0)->member))
296 :
297 : /**
298 : * @brief Concatenate input arguments
299 : *
300 : * Concatenate provided tokens into a combined token during the preprocessor pass.
301 : * This can be used to, for ex., build an identifier out of multiple parts,
302 : * where one of those parts may be, for ex, a number, another macro, or a macro argument.
303 : *
304 : * @param ... Tokens to concatencate
305 : *
306 : * @return Concatenated token.
307 : */
308 1 : #define CONCAT(...) UTIL_CAT(_CONCAT_, NUM_VA_ARGS_LESS_1(__VA_ARGS__))(__VA_ARGS__)
309 :
310 : /**
311 : * @brief Check if @p ptr is aligned to @p align alignment
312 : */
313 1 : #define IS_ALIGNED(ptr, align) (((uintptr_t)(ptr)) % (align) == 0)
314 :
315 : /**
316 : * @brief Value of @p x rounded up to the next multiple of @p align.
317 : */
318 1 : #define ROUND_UP(x, align) \
319 : ((((unsigned long)(x) + ((unsigned long)(align) - 1)) / (unsigned long)(align)) * \
320 : (unsigned long)(align))
321 :
322 : /**
323 : * @brief Value of @p x rounded down to the previous multiple of @p align.
324 : */
325 1 : #define ROUND_DOWN(x, align) \
326 : (((unsigned long)(x) / (unsigned long)(align)) * (unsigned long)(align))
327 :
328 : /** @brief Value of @p x rounded up to the next word boundary. */
329 1 : #define WB_UP(x) ROUND_UP(x, sizeof(void *))
330 :
331 : /** @brief Value of @p x rounded down to the previous word boundary. */
332 1 : #define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
333 :
334 : /**
335 : * @brief Divide and round up.
336 : *
337 : * Example:
338 : * @code{.c}
339 : * DIV_ROUND_UP(1, 2); // 1
340 : * DIV_ROUND_UP(3, 2); // 2
341 : * @endcode
342 : *
343 : * @param n Numerator.
344 : * @param d Denominator.
345 : *
346 : * @return The result of @p n / @p d, rounded up.
347 : */
348 1 : #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
349 :
350 : /**
351 : * @brief Divide and round to the nearest integer.
352 : *
353 : * Example:
354 : * @code{.c}
355 : * DIV_ROUND_CLOSEST(5, 2); // 3
356 : * DIV_ROUND_CLOSEST(5, -2); // -3
357 : * DIV_ROUND_CLOSEST(5, 3); // 2
358 : * @endcode
359 : *
360 : * @param n Numerator.
361 : * @param d Denominator.
362 : *
363 : * @return The result of @p n / @p d, rounded to the nearest integer.
364 : */
365 1 : #define DIV_ROUND_CLOSEST(n, d) \
366 : (((((__typeof__(n))-1) < 0) && (((__typeof__(d))-1) < 0) && ((n) < 0) ^ ((d) < 0)) \
367 : ? ((n) - ((d) / 2)) / (d) \
368 : : ((n) + ((d) / 2)) / (d))
369 :
370 : /**
371 : * @cond INTERNAL_HIDDEN
372 : */
373 : #define Z_INTERNAL_MAX(a, b) (((a) > (b)) ? (a) : (b))
374 : #define Z_INTERNAL_MIN(a, b) (((a) < (b)) ? (a) : (b))
375 :
376 : #define _minmax_unique(op, a, b, ua, ub) ({ \
377 : __typeof__(a) ua = (a); \
378 : __typeof__(b) ub = (b); \
379 : op(ua, ub); \
380 : })
381 :
382 : #define _minmax_cnt(op, a, b, cnt) \
383 : _minmax_unique(op, a, b, UTIL_CAT(_value_a_, cnt), UTIL_CAT(_value_b_, cnt))
384 :
385 : #define _minmax3_unique(op, a, b, c, ua, ub, uc) ({ \
386 : __typeof__(a) ua = (a); \
387 : __typeof__(b) ub = (b); \
388 : __typeof__(c) uc = (c); \
389 : op(ua, op(ub, uc)); \
390 : })
391 :
392 : #define _minmax3_cnt(op, a, b, c, cnt) \
393 : _minmax3_unique(op, a, b, c, \
394 : UTIL_CAT(_value_a_, cnt), \
395 : UTIL_CAT(_value_b_, cnt), \
396 : UTIL_CAT(_value_c_, cnt))
397 : /**
398 : * @endcond
399 : */
400 :
401 : #ifndef MAX
402 : /**
403 : * @brief Obtain the maximum of two values.
404 : *
405 : * @note Arguments are evaluated twice. Use @ref max for a single evaluation
406 : * version.
407 : *
408 : * @param a First value.
409 : * @param b Second value.
410 : *
411 : * @returns Maximum value of @p a and @p b.
412 : */
413 1 : #define MAX(a, b) Z_INTERNAL_MAX(a, b)
414 : #endif
415 :
416 : #ifndef __cplusplus
417 : /** @brief Return larger value of two provided expressions.
418 : *
419 : * Macro ensures that expressions are evaluated only once.
420 : *
421 : * @note Macro has limited usage compared to the standard macro as it cannot be
422 : * used:
423 : * - to generate constant integer, e.g. __aligned(max(4,5))
424 : * - static variable, e.g. array like static uint8_t array[max(...)];
425 : */
426 1 : #define max(a, b) _minmax_cnt(Z_INTERNAL_MAX, a, b, __COUNTER__)
427 : #endif
428 :
429 : /** @brief Return larger value of three provided expressions.
430 : *
431 : * Macro ensures that expressions are evaluated only once. See @ref max for
432 : * macro limitations.
433 : */
434 1 : #define max3(a, b, c) _minmax3_cnt(Z_INTERNAL_MAX, a, b, c, __COUNTER__)
435 :
436 : #ifndef MIN
437 : /**
438 : * @brief Obtain the minimum of two values.
439 : *
440 : * @note Arguments are evaluated twice. Use @ref min for a single evaluation
441 : * version.
442 : *
443 : * @param a First value.
444 : * @param b Second value.
445 : *
446 : * @returns Minimum value of @p a and @p b.
447 : */
448 1 : #define MIN(a, b) Z_INTERNAL_MIN(a, b)
449 : #endif
450 :
451 : #ifndef __cplusplus
452 : /** @brief Return smaller value of two provided expressions.
453 : *
454 : * Macro ensures that expressions are evaluated only once. See @ref max for
455 : * macro limitations.
456 : */
457 1 : #define min(a, b) _minmax_cnt(Z_INTERNAL_MIN, a, b, __COUNTER__)
458 : #endif
459 :
460 : /** @brief Return smaller value of three provided expressions.
461 : *
462 : * Macro ensures that expressions are evaluated only once. See @ref max for
463 : * macro limitations.
464 : */
465 1 : #define min3(a, b, c) _minmax3_cnt(Z_INTERNAL_MIN, a, b, c, __COUNTER__)
466 :
467 :
468 : #ifndef MAX_FROM_LIST
469 : /**
470 : * @brief Returns the maximum of a single value (base case).
471 : * @param a The value.
472 : * @returns The value `a`.
473 : */
474 : #define Z_MAX_1(a) a
475 :
476 : /**
477 : * @brief Returns the maximum of two values.
478 : *
479 : * @note Arguments are evaluated multiple times.
480 : *
481 : * @param a First value.
482 : * @param b Second value.
483 : * @returns Maximum value of @p a and @p b.
484 : */
485 : #define Z_MAX_2(a, b) ((a) > (b) ? (a) : (b))
486 :
487 : /**
488 : * @brief Returns the maximum of three values.
489 : * @note Arguments may be evaluated multiple times.
490 : * @param a First value.
491 : * @param b Second value.
492 : * @param c Third value.
493 : * @returns Maximum value of @p a, @p b, and @p c.
494 : */
495 : #define Z_MAX_3(a, b, c) Z_MAX_2(a, Z_MAX_2(b, c))
496 :
497 : /**
498 : * @brief Returns the maximum of four values.
499 : * @note Arguments may be evaluated multiple times.
500 : * @param a First value.
501 : * @param b Second value.
502 : * @param c Third value.
503 : * @param d Fourth value.
504 : * @returns Maximum value of @p a, @p b, @p c, and @p d.
505 : */
506 : #define Z_MAX_4(a, b, c, d) Z_MAX_2(Z_MAX_2(a, b), Z_MAX_2(c, d))
507 :
508 : /**
509 : * @brief Returns the maximum of five values.
510 : * @note Arguments may be evaluated multiple times.
511 : */
512 : #define Z_MAX_5(a, b, c, d, e) Z_MAX_2(Z_MAX_4(a, b, c, d), e)
513 :
514 : /**
515 : * @brief Returns the maximum of six values.
516 : * @note Arguments may be evaluated multiple times.
517 : */
518 : #define Z_MAX_6(a, b, c, d, e, f) Z_MAX_2(Z_MAX_5(a, b, c, d, e), f)
519 :
520 : /**
521 : * @brief Returns the maximum of seven values.
522 : * @note Arguments may be evaluated multiple times.
523 : */
524 : #define Z_MAX_7(a, b, c, d, e, f, g) Z_MAX_2(Z_MAX_6(a, b, c, d, e, f), g)
525 :
526 : /**
527 : * @brief Returns the maximum of eight values.
528 : * @note Arguments may be evaluated multiple times.
529 : */
530 : #define Z_MAX_8(a, b, c, d, e, f, g, h) Z_MAX_2(Z_MAX_7(a, b, c, d, e, f, g), h)
531 :
532 : /**
533 : * @brief Returns the maximum of nine values.
534 : * @note Arguments may be evaluated multiple times.
535 : */
536 : #define Z_MAX_9(a, b, c, d, e, f, g, h, i) Z_MAX_2(Z_MAX_8(a, b, c, d, e, f, g, h), i)
537 :
538 : /**
539 : * @brief Returns the maximum of ten values.
540 : * @note Arguments may be evaluated multiple times.
541 : */
542 : #define Z_MAX_10(a, b, c, d, e, f, g, h, i, j) Z_MAX_2(Z_MAX_9(a, b, c, d, e, f, g, h, i), j)
543 :
544 : /**
545 : * @brief Helper macro to select the correct MAX_N macro.
546 : *
547 : * This macro uses the argument-counting trick to pick the correct
548 : * `Z_MAX_N` macro name from the arguments provided to `MAX_FROM_LIST`.
549 : * The 10th argument (or 11th including `NAME`) effectively becomes the
550 : * macro name to use.
551 : *
552 : * @param _1 Positional argument 1.
553 : * @param _2 Positional argument 2.
554 : * @param _3 Positional argument 3.
555 : * @param _4 Positional argument 4.
556 : * @param _5 Positional argument 5.
557 : * @param _6 Positional argument 6.
558 : * @param _7 Positional argument 7.
559 : * @param _8 Positional argument 8.
560 : * @param _9 Positional argument 9.
561 : * @param _10 Positional argument 10.
562 : * @param NAME The macro name to be selected.
563 : * @param ... Additional arguments.
564 : * @returns The selected macro name `NAME`.
565 : */
566 : #define Z_GET_MAX_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, NAME, ...) NAME
567 :
568 : /**
569 : * @brief Finds the maximum value from a list of 1 to 10 arguments.
570 : *
571 : * Dispatches to the appropriate internal `Z_MAX_N` macro based on the number of
572 : * arguments provided.
573 : *
574 : * Example Usage:
575 : * MAX_FROM_LIST(1, 5, 2)
576 : * MAX_FROM_LIST(10)
577 : *
578 : * @note Arguments may be evaluated multiple times by the underlying
579 : * `Z_MAX_N` macros. Avoid expressions with side effects.
580 : *
581 : * @param ... A list of 1 to 10 values to compare.
582 : * @returns The maximum value among the arguments.
583 : */
584 1 : #define MAX_FROM_LIST(...) \
585 : Z_GET_MAX_MACRO(__VA_ARGS__, Z_MAX_10, Z_MAX_9, Z_MAX_8, Z_MAX_7, Z_MAX_6, Z_MAX_5, \
586 : Z_MAX_4, Z_MAX_3, Z_MAX_2, Z_MAX_1)(__VA_ARGS__)
587 : #endif
588 :
589 : #ifndef CLAMP
590 : /**
591 : * @brief Clamp a value to a given range.
592 : *
593 : * @note Arguments are evaluated multiple times. Use @ref clamp for a single
594 : * evaluation version.
595 : *
596 : * @param val Value to be clamped.
597 : * @param low Lowest allowed value (inclusive).
598 : * @param high Highest allowed value (inclusive).
599 : *
600 : * @returns Clamped value.
601 : */
602 1 : #define CLAMP(val, low, high) (((val) <= (low)) ? (low) : Z_INTERNAL_MIN(val, high))
603 : #endif
604 :
605 : #ifndef __cplusplus
606 : /** @brief Return a value clamped to a given range.
607 : *
608 : * Macro ensures that expressions are evaluated only once. See @ref max for
609 : * macro limitations.
610 : */
611 1 : #define clamp(val, low, high) ({ \
612 : /* random suffix to avoid naming conflict */ \
613 : __typeof__(val) _value_val_ = (val); \
614 : __typeof__(low) _value_low_ = (low); \
615 : __typeof__(high) _value_high_ = (high); \
616 : (_value_val_ < _value_low_) ? _value_low_ : \
617 : (_value_val_ > _value_high_) ? _value_high_ : \
618 : _value_val_; \
619 : })
620 : #endif
621 :
622 : /**
623 : * @brief Checks if a value is within range.
624 : *
625 : * @note @p val is evaluated twice.
626 : *
627 : * @param val Value to be checked.
628 : * @param min Lower bound (inclusive).
629 : * @param max Upper bound (inclusive).
630 : *
631 : * @retval true If value is within range
632 : * @retval false If the value is not within range
633 : */
634 1 : #define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
635 :
636 : /**
637 : * Find number of contiguous bits which are not set in the bit mask (32 bits).
638 : *
639 : * It is possible to return immediately when requested number of bits is found or
640 : * iterate over whole mask and return the best fit (smallest from available options).
641 : *
642 : * @param[in] mask 32 bit mask.
643 : * @param[in] num_bits Number of bits to find.
644 : * @param[in] total_bits Total number of LSB bits that can be used in the mask.
645 : * @param[in] first_match If true returns when first match is found, else returns the best fit.
646 : *
647 : * @retval -1 Contiguous bits not found.
648 : * @retval non-negative Starting index of the bits group.
649 : */
650 1 : int bitmask_find_gap(uint32_t mask, size_t num_bits, size_t total_bits, bool first_match);
651 :
652 : /**
653 : * @brief Is @p x a power of two?
654 : * @param x value to check
655 : * @return true if @p x is a power of two, false otherwise
656 : */
657 1 : static inline bool is_power_of_two(unsigned int x)
658 : {
659 : return IS_POWER_OF_TWO(x);
660 : }
661 :
662 : /**
663 : * @brief Is @p p equal to ``NULL``?
664 : *
665 : * Some macros may need to check their arguments against NULL to support
666 : * multiple use-cases, but NULL checks can generate warnings if such a macro
667 : * is used in contexts where that particular argument can never be NULL.
668 : *
669 : * The warnings can be triggered if:
670 : * a) all macros are expanded (e.g. when using CONFIG_COMPILER_SAVE_TEMPS=y)
671 : * or
672 : * b) tracking of macro expansions are turned off (-ftrack-macro-expansion=0)
673 : *
674 : * The warnings can be circumvented by using this inline function for doing
675 : * the NULL check within the macro. The compiler is still able to optimize the
676 : * NULL check out at a later stage.
677 : *
678 : * @param p Pointer to check
679 : * @return true if @p p is equal to ``NULL``, false otherwise
680 : */
681 1 : static ALWAYS_INLINE bool is_null_no_warn(void *p)
682 : {
683 : return p == NULL;
684 : }
685 :
686 : /**
687 : * @brief Arithmetic shift right
688 : * @param value value to shift
689 : * @param shift number of bits to shift
690 : * @return @p value shifted right by @p shift; opened bit positions are
691 : * filled with the sign bit
692 : */
693 1 : static inline int64_t arithmetic_shift_right(int64_t value, uint8_t shift)
694 : {
695 : int64_t sign_ext;
696 :
697 : if (shift == 0U) {
698 : return value;
699 : }
700 :
701 : /* extract sign bit */
702 : sign_ext = (value >> 63) & 1;
703 :
704 : /* make all bits of sign_ext be the same as the value's sign bit */
705 : sign_ext = -sign_ext;
706 :
707 : /* shift value and fill opened bit positions with sign bit */
708 : return (value >> shift) | (sign_ext << (64 - shift));
709 : }
710 :
711 : /**
712 : * @brief byte by byte memcpy.
713 : *
714 : * Copy `size` bytes of `src` into `dest`. This is guaranteed to be done byte by byte.
715 : *
716 : * @param dst Pointer to the destination memory.
717 : * @param src Pointer to the source of the data.
718 : * @param size The number of bytes to copy.
719 : */
720 1 : static inline void bytecpy(void *dst, const void *src, size_t size)
721 : {
722 : size_t i;
723 :
724 : for (i = 0; i < size; ++i) {
725 : ((volatile uint8_t *)dst)[i] = ((volatile const uint8_t *)src)[i];
726 : }
727 : }
728 :
729 : /**
730 : * @brief byte by byte swap.
731 : *
732 : * Swap @a size bytes between memory regions @a a and @a b. This is
733 : * guaranteed to be done byte by byte.
734 : *
735 : * @param a Pointer to the first memory region.
736 : * @param b Pointer to the second memory region.
737 : * @param size The number of bytes to swap.
738 : */
739 1 : static inline void byteswp(void *a, void *b, size_t size)
740 : {
741 : uint8_t t;
742 : uint8_t *aa = (uint8_t *)a;
743 : uint8_t *bb = (uint8_t *)b;
744 :
745 : for (; size > 0; --size) {
746 : t = *aa;
747 : *aa++ = *bb;
748 : *bb++ = t;
749 : }
750 : }
751 :
752 : /**
753 : * @brief Convert a single character into a hexadecimal nibble.
754 : *
755 : * @param c The character to convert
756 : * @param x The address of storage for the converted number.
757 : *
758 : * @return Zero on success or (negative) error code otherwise.
759 : */
760 1 : int char2hex(char c, uint8_t *x);
761 :
762 : /**
763 : * @brief Convert a single hexadecimal nibble into a character.
764 : *
765 : * @param c The number to convert
766 : * @param x The address of storage for the converted character.
767 : *
768 : * @return Zero on success or (negative) error code otherwise.
769 : */
770 1 : int hex2char(uint8_t x, char *c);
771 :
772 : /**
773 : * @brief Convert a binary array into string representation.
774 : *
775 : * @param buf The binary array to convert
776 : * @param buflen The length of the binary array to convert
777 : * @param hex Address of where to store the string representation.
778 : * @param hexlen Size of the storage area for string representation.
779 : *
780 : * @return The length of the converted string, or 0 if an error occurred.
781 : */
782 1 : size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
783 :
784 : /**
785 : * @brief Convert a hexadecimal string into a binary array.
786 : *
787 : * @param hex The hexadecimal string to convert
788 : * @param hexlen The length of the hexadecimal string to convert.
789 : * @param buf Address of where to store the binary data
790 : * @param buflen Size of the storage area for binary data
791 : *
792 : * @return The length of the binary array, or 0 if an error occurred.
793 : */
794 1 : size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
795 :
796 : /**
797 : * @brief Convert a binary coded decimal (BCD 8421) value to binary.
798 : *
799 : * @param bcd BCD 8421 value to convert.
800 : *
801 : * @return Binary representation of input value.
802 : */
803 1 : static inline uint8_t bcd2bin(uint8_t bcd)
804 : {
805 : return ((10 * (bcd >> 4)) + (bcd & 0x0F));
806 : }
807 :
808 : /**
809 : * @brief Convert a binary value to binary coded decimal (BCD 8421).
810 : *
811 : * @param bin Binary value to convert.
812 : *
813 : * @return BCD 8421 representation of input value.
814 : */
815 1 : static inline uint8_t bin2bcd(uint8_t bin)
816 : {
817 : return (((bin / 10) << 4) | (bin % 10));
818 : }
819 :
820 : /**
821 : * @brief Convert a uint8_t into a decimal string representation.
822 : *
823 : * Convert a uint8_t value into its ASCII decimal string representation.
824 : * The string is terminated if there is enough space in buf.
825 : *
826 : * @param buf Address of where to store the string representation.
827 : * @param buflen Size of the storage area for string representation.
828 : * @param value The value to convert to decimal string
829 : *
830 : * @return The length of the converted string (excluding terminator if
831 : * any), or 0 if an error occurred.
832 : */
833 1 : uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);
834 :
835 : /**
836 : * @brief Sign extend an 8, 16 or 32 bit value using the index bit as sign bit.
837 : *
838 : * @param value The value to sign expand.
839 : * @param index 0 based bit index to sign bit (0 to 31)
840 : */
841 1 : static inline int32_t sign_extend(uint32_t value, uint8_t index)
842 : {
843 : __ASSERT_NO_MSG(index <= 31);
844 :
845 : uint8_t shift = 31 - index;
846 :
847 : return (int32_t)(value << shift) >> shift;
848 : }
849 :
850 : /**
851 : * @brief Sign extend a 64 bit value using the index bit as sign bit.
852 : *
853 : * @param value The value to sign expand.
854 : * @param index 0 based bit index to sign bit (0 to 63)
855 : */
856 1 : static inline int64_t sign_extend_64(uint64_t value, uint8_t index)
857 : {
858 : __ASSERT_NO_MSG(index <= 63);
859 :
860 : uint8_t shift = 63 - index;
861 :
862 : return (int64_t)(value << shift) >> shift;
863 : }
864 :
865 : #define __z_log2d(x) (32 - __builtin_clz(x) - 1)
866 : #define __z_log2q(x) (64 - __builtin_clzll(x) - 1)
867 : #define __z_log2(x) (sizeof(__typeof__(x)) > 4 ? __z_log2q(x) : __z_log2d(x))
868 :
869 : /**
870 : * @brief Compute log2(x)
871 : *
872 : * @note This macro expands its argument multiple times (to permit use
873 : * in constant expressions), which must not have side effects.
874 : *
875 : * @param x An unsigned integral value to compute logarithm of (positive only)
876 : *
877 : * @return log2(x) when 1 <= x <= max(x), -1 when x < 1
878 : */
879 1 : #define LOG2(x) ((x) < 1 ? -1 : __z_log2(x))
880 :
881 : /**
882 : * @brief Compute ceil(log2(x))
883 : *
884 : * @note This macro expands its argument multiple times (to permit use
885 : * in constant expressions), which must not have side effects.
886 : *
887 : * @param x An unsigned integral value
888 : *
889 : * @return ceil(log2(x)) when 1 <= x <= max(type(x)), 0 when x < 1
890 : */
891 1 : #define LOG2CEIL(x) ((x) <= 1 ? 0 : __z_log2((x) - 1) + 1)
892 :
893 : /**
894 : * @brief Compute next highest power of two
895 : *
896 : * Equivalent to 2^ceil(log2(x))
897 : *
898 : * @note This macro expands its argument multiple times (to permit use
899 : * in constant expressions), which must not have side effects.
900 : *
901 : * @param x An unsigned integral value
902 : *
903 : * @return 2^ceil(log2(x)) or 0 if 2^ceil(log2(x)) would saturate 64-bits
904 : */
905 1 : #define NHPOT(x) ((x) < 1 ? 1 : ((x) > (1ULL << 63) ? 0 : 1ULL << LOG2CEIL(x)))
906 :
907 : /**
908 : * @brief Determine if a buffer exceeds highest address
909 : *
910 : * This macro determines if a buffer identified by a starting address @a addr
911 : * and length @a buflen spans a region of memory that goes beyond the highest
912 : * possible address (thereby resulting in a pointer overflow).
913 : *
914 : * @param addr Buffer starting address
915 : * @param buflen Length of the buffer
916 : *
917 : * @return true if pointer overflow detected, false otherwise
918 : */
919 : #define Z_DETECT_POINTER_OVERFLOW(addr, buflen) \
920 : (((buflen) != 0) && ((UINTPTR_MAX - (uintptr_t)(addr)) <= ((uintptr_t)((buflen) - 1))))
921 :
922 : /**
923 : * @brief XOR n bytes
924 : *
925 : * @param dst Destination of where to store result. Shall be @p len bytes.
926 : * @param src1 First source. Shall be @p len bytes.
927 : * @param src2 Second source. Shall be @p len bytes.
928 : * @param len Number of bytes to XOR.
929 : */
930 1 : static inline void mem_xor_n(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, size_t len)
931 : {
932 : while (len--) {
933 : *dst++ = *src1++ ^ *src2++;
934 : }
935 : }
936 :
937 : /**
938 : * @brief XOR 32 bits
939 : *
940 : * @param dst Destination of where to store result. Shall be 32 bits.
941 : * @param src1 First source. Shall be 32 bits.
942 : * @param src2 Second source. Shall be 32 bits.
943 : */
944 1 : static inline void mem_xor_32(uint8_t dst[4], const uint8_t src1[4], const uint8_t src2[4])
945 : {
946 : mem_xor_n(dst, src1, src2, 4U);
947 : }
948 :
949 : /**
950 : * @brief XOR 128 bits
951 : *
952 : * @param dst Destination of where to store result. Shall be 128 bits.
953 : * @param src1 First source. Shall be 128 bits.
954 : * @param src2 Second source. Shall be 128 bits.
955 : */
956 1 : static inline void mem_xor_128(uint8_t dst[16], const uint8_t src1[16], const uint8_t src2[16])
957 : {
958 : mem_xor_n(dst, src1, src2, 16);
959 : }
960 :
961 : /**
962 : * @brief Compare memory areas. The same way as `memcmp` it assume areas to be
963 : * the same length
964 : *
965 : * @param m1 First memory area to compare, cannot be NULL even if length is 0
966 : * @param m2 Second memory area to compare, cannot be NULL even if length is 0
967 : * @param n First n bytes of @p m1 and @p m2 to compares
968 : *
969 : * @returns true if the @p n first bytes of @p m1 and @p m2 are the same, else
970 : * false
971 : */
972 1 : static inline bool util_memeq(const void *m1, const void *m2, size_t n)
973 : {
974 : return memcmp(m1, m2, n) == 0;
975 : }
976 :
977 : /**
978 : * @brief Compare memory areas and their length
979 : *
980 : * If the length are 0, return true.
981 : *
982 : * @param m1 First memory area to compare, cannot be NULL even if length is 0
983 : * @param len1 Length of the first memory area to compare
984 : * @param m2 Second memory area to compare, cannot be NULL even if length is 0
985 : * @param len2 Length of the second memory area to compare
986 : *
987 : * @returns true if both the length of the memory areas and their content are
988 : * equal else false
989 : */
990 1 : static inline bool util_eq(const void *m1, size_t len1, const void *m2, size_t len2)
991 : {
992 : return len1 == len2 && (m1 == m2 || util_memeq(m1, m2, len1));
993 : }
994 :
995 : /**
996 : * @brief Returns the number of bits set in a value
997 : *
998 : * @param value The value to count number of bits set of
999 : * @param len The number of octets in @p value
1000 : */
1001 1 : static inline size_t sys_count_bits(const void *value, size_t len)
1002 : {
1003 : size_t cnt = 0U;
1004 : size_t i = 0U;
1005 :
1006 : #ifdef POPCOUNT
1007 : for (; i < len / sizeof(unsigned int); i++) {
1008 : unsigned int val;
1009 : (void)memcpy(&val, (const uint8_t *)value + i * sizeof(unsigned int),
1010 : sizeof(unsigned int));
1011 :
1012 : cnt += POPCOUNT(val);
1013 : }
1014 : i *= sizeof(unsigned int); /* convert to a uint8_t index for the remainder (if any) */
1015 : #endif
1016 :
1017 : for (; i < len; i++) {
1018 : uint8_t value_u8 = ((const uint8_t *)value)[i];
1019 :
1020 : /* Implements Brian Kernighan’s Algorithm to count bits */
1021 : while (value_u8) {
1022 : value_u8 &= (value_u8 - 1);
1023 : cnt++;
1024 : }
1025 : }
1026 :
1027 : return cnt;
1028 : }
1029 :
1030 : #ifdef __cplusplus
1031 : }
1032 : #endif
1033 :
1034 : /* This file must be included at the end of the !_ASMLANGUAGE guard.
1035 : * It depends on macros defined in this file above which cannot be forward declared.
1036 : */
1037 : #include <zephyr/sys/time_units.h>
1038 :
1039 : #endif /* !_ASMLANGUAGE */
1040 :
1041 : /** @brief Number of bytes in @p x kibibytes */
1042 : #ifdef _LINKER
1043 : /* This is used in linker scripts so need to avoid type casting there */
1044 1 : #define KB(x) ((x) << 10)
1045 : #else
1046 : #define KB(x) (((size_t)(x)) << 10)
1047 : #endif
1048 : /** @brief Number of bytes in @p x mebibytes */
1049 1 : #define MB(x) (KB(x) << 10)
1050 : /** @brief Number of bytes in @p x gibibytes */
1051 1 : #define GB(x) (MB(x) << 10)
1052 :
1053 : /** @brief Number of Hz in @p x kHz */
1054 1 : #define KHZ(x) ((x) * 1000)
1055 : /** @brief Number of Hz in @p x MHz */
1056 1 : #define MHZ(x) (KHZ(x) * 1000)
1057 :
1058 : /**
1059 : * @brief For the POSIX architecture add a minimal delay in a busy wait loop.
1060 : * For other architectures this is a no-op.
1061 : *
1062 : * In the POSIX ARCH, code takes zero simulated time to execute,
1063 : * so busy wait loops become infinite loops, unless we
1064 : * force the loop to take a bit of time.
1065 : * Include this macro in all busy wait/spin loops
1066 : * so they will also work when building for the POSIX architecture.
1067 : *
1068 : * @param t Time in microseconds we will busy wait
1069 : */
1070 : #if defined(CONFIG_ARCH_POSIX)
1071 : #define Z_SPIN_DELAY(t) k_busy_wait(t)
1072 : #else
1073 : #define Z_SPIN_DELAY(t)
1074 : #endif
1075 :
1076 : /**
1077 : * @brief Wait for an expression to return true with a timeout
1078 : *
1079 : * Spin on an expression with a timeout and optional delay between iterations
1080 : *
1081 : * Commonly needed when waiting on hardware to complete an asynchronous
1082 : * request to read/write/initialize/reset, but useful for any expression.
1083 : *
1084 : * @param expr Truth expression upon which to poll, e.g.: XYZREG & XYZREG_EN
1085 : * @param timeout Timeout to wait for in microseconds, e.g.: 1000 (1ms)
1086 : * @param delay_stmt Delay statement to perform each poll iteration
1087 : * e.g.: NULL, k_yield(), k_msleep(1) or k_busy_wait(1)
1088 : *
1089 : * @retval expr As a boolean return, if false then it has timed out.
1090 : */
1091 1 : #define WAIT_FOR(expr, timeout, delay_stmt) \
1092 : ({ \
1093 : uint32_t _wf_cycle_count = k_us_to_cyc_ceil32(timeout); \
1094 : uint32_t _wf_start = k_cycle_get_32(); \
1095 : while (!(expr) && (_wf_cycle_count > (k_cycle_get_32() - _wf_start))) { \
1096 : delay_stmt; \
1097 : Z_SPIN_DELAY(10); \
1098 : } \
1099 : (expr); \
1100 : })
1101 :
1102 : /**
1103 : * @}
1104 : */
1105 :
1106 : #endif /* ZEPHYR_INCLUDE_SYS_UTIL_H_ */
|