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
19 /* needs to be outside _ASMLANGUAGE so 'true' and 'false' can turn
20 * into '1' and '0' for asm or linker scripts
21 */
22 #include <stdbool.h>
23
24 #ifndef _ASMLANGUAGE
25
26 #include <zephyr/types.h>
27 #include <stddef.h>
28
29 /** @brief Number of bits that make up a type */
30 #define NUM_BITS(t) (sizeof(t) * 8)
31
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35
36 /**
37 * @defgroup sys-util Utility Functions
38 * @ingroup utilities
39 * @{
40 */
41
42 /** @brief Cast @p x, a pointer, to an unsigned integer. */
43 #define POINTER_TO_UINT(x) ((uintptr_t) (x))
44 /** @brief Cast @p x, an unsigned integer, to a <tt>void*</tt>. */
45 #define UINT_TO_POINTER(x) ((void *) (uintptr_t) (x))
46 /** @brief Cast @p x, a pointer, to a signed integer. */
47 #define POINTER_TO_INT(x) ((intptr_t) (x))
48 /** @brief Cast @p x, a signed integer, to a <tt>void*</tt>. */
49 #define INT_TO_POINTER(x) ((void *) (intptr_t) (x))
50
51 #if !(defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__) && defined(__SIZEOF_LONG_LONG__))
52 # error Missing required predefined macros for BITS_PER_LONG calculation
53 #endif
54
55 /** Number of bits in a long int. */
56 #define BITS_PER_LONG (__CHAR_BIT__ * __SIZEOF_LONG__)
57
58 /** Number of bits in a long long int. */
59 #define BITS_PER_LONG_LONG (__CHAR_BIT__ * __SIZEOF_LONG_LONG__)
60
61 /**
62 * @brief Create a contiguous bitmask starting at bit position @p l
63 * and ending at position @p h.
64 */
65 #define GENMASK(h, l) \
66 (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
67
68 /**
69 * @brief Create a contiguous 64-bit bitmask starting at bit position @p l
70 * and ending at position @p h.
71 */
72 #define GENMASK64(h, l) \
73 (((~0ULL) - (1ULL << (l)) + 1) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))
74
75 /** @brief Extract the Least Significant Bit from @p value. */
76 #define LSB_GET(value) ((value) & -(value))
77
78 /**
79 * @brief Extract a bitfield element from @p value corresponding to
80 * the field mask @p mask.
81 */
82 #define FIELD_GET(mask, value) (((value) & (mask)) / LSB_GET(mask))
83
84 /**
85 * @brief Prepare a bitfield element using @p value with @p mask representing
86 * its field position and width. The result should be combined
87 * with other fields using a logical OR.
88 */
89 #define FIELD_PREP(mask, value) (((value) * LSB_GET(mask)) & (mask))
90
91 /** @brief 0 if @p cond is true-ish; causes a compile error otherwise. */
92 #define ZERO_OR_COMPILE_ERROR(cond) ((int) sizeof(char[1 - 2 * !(cond)]) - 1)
93
94 #if defined(__cplusplus)
95
96 /* The built-in function used below for type checking in C is not
97 * supported by GNU C++.
98 */
99 #define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
100
101 #else /* __cplusplus */
102
103 /**
104 * @brief Zero if @p array has an array type, a compile error otherwise
105 *
106 * This macro is available only from C, not C++.
107 */
108 #define IS_ARRAY(array) \
109 ZERO_OR_COMPILE_ERROR( \
110 !__builtin_types_compatible_p(__typeof__(array), \
111 __typeof__(&(array)[0])))
112
113 /**
114 * @brief Number of elements in the given @p array
115 *
116 * In C++, due to language limitations, this will accept as @p array
117 * any type that implements <tt>operator[]</tt>. The results may not be
118 * particularly meaningful in this case.
119 *
120 * In C, passing a pointer as @p array causes a compile error.
121 */
122 #define ARRAY_SIZE(array) \
123 ((size_t) (IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))
124
125 #endif /* __cplusplus */
126
127 /**
128 * @brief Whether @p ptr is an element of @p array
129 *
130 * This macro can be seen as a slightly stricter version of @ref PART_OF_ARRAY
131 * in that it also ensures that @p ptr is aligned to an array-element boundary
132 * of @p array.
133 *
134 * In C, passing a pointer as @p array causes a compile error.
135 *
136 * @param array the array in question
137 * @param ptr the pointer to check
138 *
139 * @return 1 if @p ptr is part of @p array, 0 otherwise
140 */
141 #define IS_ARRAY_ELEMENT(array, ptr) \
142 ((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) && \
143 POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]) && \
144 (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) % sizeof((array)[0]) == 0)
145
146 /**
147 * @brief Index of @p ptr within @p array
148 *
149 * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
150 * when @p ptr does not fall into the range of @p array or when @p ptr
151 * is not aligned to an array-element boundary 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 pointer to an element of @p array
157 *
158 * @return the array index of @p ptr within @p array, on success
159 */
160 #define ARRAY_INDEX(array, ptr) \
161 ({ \
162 __ASSERT_NO_MSG(IS_ARRAY_ELEMENT(array, ptr)); \
163 (__typeof__((array)[0]) *)(ptr) - (array); \
164 })
165
166 /**
167 * @brief Check if a pointer @p ptr lies within @p array.
168 *
169 * In C but not C++, this causes a compile error if @p array is not an array
170 * (e.g. if @p ptr and @p array are mixed up).
171 *
172 * @param array an array
173 * @param ptr a pointer
174 * @return 1 if @p ptr is part of @p array, 0 otherwise
175 */
176 #define PART_OF_ARRAY(array, ptr) \
177 ((ptr) && POINTER_TO_UINT(array) <= POINTER_TO_UINT(ptr) && \
178 POINTER_TO_UINT(ptr) < POINTER_TO_UINT(&(array)[ARRAY_SIZE(array)]))
179
180 /**
181 * @brief Array-index of @p ptr within @p array, rounded down
182 *
183 * This macro behaves much like @ref ARRAY_INDEX with the notable
184 * difference that it accepts any @p ptr in the range of @p array rather than
185 * exclusively a @p ptr aligned to an array-element boundary of @p array.
186 *
187 * With `CONFIG_ASSERT=y`, this macro will trigger a runtime assertion
188 * when @p ptr does not fall into the range of @p array.
189 *
190 * In C, passing a pointer as @p array causes a compile error.
191 *
192 * @param array the array in question
193 * @param ptr pointer to an element of @p array
194 *
195 * @return the array index of @p ptr within @p array, on success
196 */
197 #define ARRAY_INDEX_FLOOR(array, ptr) \
198 ({ \
199 __ASSERT_NO_MSG(PART_OF_ARRAY(array, ptr)); \
200 (POINTER_TO_UINT(ptr) - POINTER_TO_UINT(array)) / sizeof((array)[0]); \
201 })
202
203 /**
204 * @brief Get a pointer to a structure containing the element
205 *
206 * Example:
207 *
208 * struct foo {
209 * int bar;
210 * };
211 *
212 * struct foo my_foo;
213 * int *ptr = &my_foo.bar;
214 *
215 * struct foo *container = CONTAINER_OF(ptr, struct foo, bar);
216 *
217 * Above, @p container points at @p my_foo.
218 *
219 * @param ptr pointer to a structure element
220 * @param type name of the type that @p ptr is an element of
221 * @param field the name of the field within the struct @p ptr points to
222 * @return a pointer to the structure that contains @p ptr
223 */
224 #define CONTAINER_OF(ptr, type, field) \
225 ((type *)(((char *)(ptr)) - offsetof(type, field)))
226
227 /**
228 * @brief Value of @p x rounded up to the next multiple of @p align,
229 * which must be a power of 2.
230 */
231 #define ROUND_UP(x, align) \
232 (((unsigned long)(x) + ((unsigned long)(align) - 1)) & \
233 ~((unsigned long)(align) - 1))
234
235 /**
236 * @brief Value of @p x rounded down to the previous multiple of @p
237 * align, which must be a power of 2.
238 */
239 #define ROUND_DOWN(x, align) \
240 ((unsigned long)(x) & ~((unsigned long)(align) - 1))
241
242 /** @brief Value of @p x rounded up to the next word boundary. */
243 #define WB_UP(x) ROUND_UP(x, sizeof(void *))
244
245 /** @brief Value of @p x rounded down to the previous word boundary. */
246 #define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
247
248 /**
249 * @brief Divide and round up.
250 *
251 * Example:
252 * @code{.c}
253 * DIV_ROUND_UP(1, 2); // 1
254 * DIV_ROUND_UP(3, 2); // 2
255 * @endcode
256 *
257 * @param n Numerator.
258 * @param d Denominator.
259 *
260 * @return The result of @p n / @p d, rounded up.
261 */
262 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
263
264 /**
265 * @brief Ceiling function applied to @p numerator / @p divider as a fraction.
266 * @deprecated Use DIV_ROUND_UP() instead.
267 */
268 #define ceiling_fraction(numerator, divider) __DEPRECATED_MACRO \
269 DIV_ROUND_UP(numerator, divider)
270
271 #ifndef MAX
272 /**
273 * @brief Obtain the maximum of two values.
274 *
275 * @note Arguments are evaluated twice. Use Z_MAX for a GCC-only, single
276 * evaluation version
277 *
278 * @param a First value.
279 * @param b Second value.
280 *
281 * @returns Maximum value of @p a and @p b.
282 */
283 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
284 #endif
285
286 #ifndef MIN
287 /**
288 * @brief Obtain the minimum of two values.
289 *
290 * @note Arguments are evaluated twice. Use Z_MIN for a GCC-only, single
291 * evaluation version
292 *
293 * @param a First value.
294 * @param b Second value.
295 *
296 * @returns Minimum value of @p a and @p b.
297 */
298 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
299 #endif
300
301 #ifndef CLAMP
302 /**
303 * @brief Clamp a value to a given range.
304 *
305 * @note Arguments are evaluated multiple times. Use Z_CLAMP for a GCC-only,
306 * single evaluation version.
307 *
308 * @param val Value to be clamped.
309 * @param low Lowest allowed value (inclusive).
310 * @param high Highest allowed value (inclusive).
311 *
312 * @returns Clamped value.
313 */
314 #define CLAMP(val, low, high) (((val) <= (low)) ? (low) : MIN(val, high))
315 #endif
316
317 /**
318 * @brief Checks if a value is within range.
319 *
320 * @note @p val is evaluated twice.
321 *
322 * @param val Value to be checked.
323 * @param min Lower bound (inclusive).
324 * @param max Upper bound (inclusive).
325 *
326 * @retval true If value is within range
327 * @retval false If the value is not within range
328 */
329 #define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
330
331 /**
332 * @brief Is @p x a power of two?
333 * @param x value to check
334 * @return true if @p x is a power of two, false otherwise
335 */
is_power_of_two(unsigned int x)336 static inline bool is_power_of_two(unsigned int x)
337 {
338 return IS_POWER_OF_TWO(x);
339 }
340
341 /**
342 * @brief Arithmetic shift right
343 * @param value value to shift
344 * @param shift number of bits to shift
345 * @return @p value shifted right by @p shift; opened bit positions are
346 * filled with the sign bit
347 */
arithmetic_shift_right(int64_t value,uint8_t shift)348 static inline int64_t arithmetic_shift_right(int64_t value, uint8_t shift)
349 {
350 int64_t sign_ext;
351
352 if (shift == 0U) {
353 return value;
354 }
355
356 /* extract sign bit */
357 sign_ext = (value >> 63) & 1;
358
359 /* make all bits of sign_ext be the same as the value's sign bit */
360 sign_ext = -sign_ext;
361
362 /* shift value and fill opened bit positions with sign bit */
363 return (value >> shift) | (sign_ext << (64 - shift));
364 }
365
366 /**
367 * @brief byte by byte memcpy.
368 *
369 * Copy `size` bytes of `src` into `dest`. This is guaranteed to be done byte by byte.
370 *
371 * @param dst Pointer to the destination memory.
372 * @param src Pointer to the source of the data.
373 * @param size The number of bytes to copy.
374 */
bytecpy(void * dst,const void * src,size_t size)375 static inline void bytecpy(void *dst, const void *src, size_t size)
376 {
377 size_t i;
378
379 for (i = 0; i < size; ++i) {
380 ((volatile uint8_t *)dst)[i] = ((volatile const uint8_t *)src)[i];
381 }
382 }
383
384 /**
385 * @brief byte by byte swap.
386 *
387 * Swap @a size bytes between memory regions @a a and @a b. This is
388 * guaranteed to be done byte by byte.
389 *
390 * @param a Pointer to the the first memory region.
391 * @param b Pointer to the the second memory region.
392 * @param size The number of bytes to swap.
393 */
byteswp(void * a,void * b,size_t size)394 static inline void byteswp(void *a, void *b, size_t size)
395 {
396 uint8_t t;
397 uint8_t *aa = (uint8_t *)a;
398 uint8_t *bb = (uint8_t *)b;
399
400 for (; size > 0; --size) {
401 t = *aa;
402 *aa++ = *bb;
403 *bb++ = t;
404 }
405 }
406
407 /**
408 * @brief Convert a single character into a hexadecimal nibble.
409 *
410 * @param c The character to convert
411 * @param x The address of storage for the converted number.
412 *
413 * @return Zero on success or (negative) error code otherwise.
414 */
415 int char2hex(char c, uint8_t *x);
416
417 /**
418 * @brief Convert a single hexadecimal nibble into a character.
419 *
420 * @param c The number to convert
421 * @param x The address of storage for the converted character.
422 *
423 * @return Zero on success or (negative) error code otherwise.
424 */
425 int hex2char(uint8_t x, char *c);
426
427 /**
428 * @brief Convert a binary array into string representation.
429 *
430 * @param buf The binary array to convert
431 * @param buflen The length of the binary array to convert
432 * @param hex Address of where to store the string representation.
433 * @param hexlen Size of the storage area for string representation.
434 *
435 * @return The length of the converted string, or 0 if an error occurred.
436 */
437 size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
438
439 /**
440 * @brief Convert a hexadecimal string into a binary array.
441 *
442 * @param hex The hexadecimal string to convert
443 * @param hexlen The length of the hexadecimal string to convert.
444 * @param buf Address of where to store the binary data
445 * @param buflen Size of the storage area for binary data
446 *
447 * @return The length of the binary array, or 0 if an error occurred.
448 */
449 size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
450
451 /**
452 * @brief Convert a binary coded decimal (BCD 8421) value to binary.
453 *
454 * @param bcd BCD 8421 value to convert.
455 *
456 * @return Binary representation of input value.
457 */
bcd2bin(uint8_t bcd)458 static inline uint8_t bcd2bin(uint8_t bcd)
459 {
460 return ((10 * (bcd >> 4)) + (bcd & 0x0F));
461 }
462
463 /**
464 * @brief Convert a binary value to binary coded decimal (BCD 8421).
465 *
466 * @param bin Binary value to convert.
467 *
468 * @return BCD 8421 representation of input value.
469 */
bin2bcd(uint8_t bin)470 static inline uint8_t bin2bcd(uint8_t bin)
471 {
472 return (((bin / 10) << 4) | (bin % 10));
473 }
474
475 /**
476 * @brief Convert a uint8_t into a decimal string representation.
477 *
478 * Convert a uint8_t value into its ASCII decimal string representation.
479 * The string is terminated if there is enough space in buf.
480 *
481 * @param buf Address of where to store the string representation.
482 * @param buflen Size of the storage area for string representation.
483 * @param value The value to convert to decimal string
484 *
485 * @return The length of the converted string (excluding terminator if
486 * any), or 0 if an error occurred.
487 */
488 uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);
489
490 /**
491 * @brief Properly truncate a NULL-terminated UTF-8 string
492 *
493 * Take a NULL-terminated UTF-8 string and ensure that if the string has been
494 * truncated (by setting the NULL terminator) earlier by other means, that
495 * the string ends with a properly formatted UTF-8 character (1-4 bytes).
496 *
497 * @htmlonly
498 * Example:
499 * char test_str[] = "€€€";
500 * char trunc_utf8[8];
501 *
502 * printf("Original : %s\n", test_str); // €€€
503 * strncpy(trunc_utf8, test_str, sizeof(trunc_utf8));
504 * trunc_utf8[sizeof(trunc_utf8) - 1] = '\0';
505 * printf("Bad : %s\n", trunc_utf8); // €€�
506 * utf8_trunc(trunc_utf8);
507 * printf("Truncated: %s\n", trunc_utf8); // €€
508 * @endhtmlonly
509 *
510 * @param utf8_str NULL-terminated string
511 *
512 * @return Pointer to the @p utf8_str
513 */
514 char *utf8_trunc(char *utf8_str);
515
516 /**
517 * @brief Copies a UTF-8 encoded string from @p src to @p dst
518 *
519 * The resulting @p dst will always be NULL terminated if @p n is larger than 0,
520 * and the @p dst string will always be properly UTF-8 truncated.
521 *
522 * @param dst The destination of the UTF-8 string.
523 * @param src The source string
524 * @param n The size of the @p dst buffer. Maximum number of characters copied
525 * is @p n - 1. If 0 nothing will be done, and the @p dst will not be
526 * NULL terminated.
527 *
528 * @return Pointer to the @p dst
529 */
530 char *utf8_lcpy(char *dst, const char *src, size_t n);
531
532 #define __z_log2d(x) (32 - __builtin_clz(x) - 1)
533 #define __z_log2q(x) (64 - __builtin_clzll(x) - 1)
534 #define __z_log2(x) (sizeof(__typeof__(x)) > 4 ? __z_log2q(x) : __z_log2d(x))
535
536 /**
537 * @brief Compute log2(x)
538 *
539 * @note This macro expands its argument multiple times (to permit use
540 * in constant expressions), which must not have side effects.
541 *
542 * @param x An unsigned integral value to compute logarithm of (positive only)
543 *
544 * @return log2(x) when 1 <= x <= max(x), -1 when x < 1
545 */
546 #define LOG2(x) ((x) < 1 ? -1 : __z_log2(x))
547
548 /**
549 * @brief Compute ceil(log2(x))
550 *
551 * @note This macro expands its argument multiple times (to permit use
552 * in constant expressions), which must not have side effects.
553 *
554 * @param x An unsigned integral value
555 *
556 * @return ceil(log2(x)) when 1 <= x <= max(type(x)), 0 when x < 1
557 */
558 #define LOG2CEIL(x) ((x) < 1 ? 0 : __z_log2((x)-1) + 1)
559
560 /**
561 * @brief Compute next highest power of two
562 *
563 * Equivalent to 2^ceil(log2(x))
564 *
565 * @note This macro expands its argument multiple times (to permit use
566 * in constant expressions), which must not have side effects.
567 *
568 * @param x An unsigned integral value
569 *
570 * @return 2^ceil(log2(x)) or 0 if 2^ceil(log2(x)) would saturate 64-bits
571 */
572 #define NHPOT(x) ((x) < 1 ? 1 : ((x) > (1ULL<<63) ? 0 : 1ULL << LOG2CEIL(x)))
573
574 #ifdef __cplusplus
575 }
576 #endif
577
578 /* This file must be included at the end of the !_ASMLANGUAGE guard.
579 * It depends on macros defined in this file above which cannot be forward declared.
580 */
581 #include <zephyr/sys/time_units.h>
582
583 #endif /* !_ASMLANGUAGE */
584
585 /** @brief Number of bytes in @p x kibibytes */
586 #ifdef _LINKER
587 /* This is used in linker scripts so need to avoid type casting there */
588 #define KB(x) ((x) << 10)
589 #else
590 #define KB(x) (((size_t)x) << 10)
591 #endif
592 /** @brief Number of bytes in @p x mebibytes */
593 #define MB(x) (KB(x) << 10)
594 /** @brief Number of bytes in @p x gibibytes */
595 #define GB(x) (MB(x) << 10)
596
597 /** @brief Number of Hz in @p x kHz */
598 #define KHZ(x) ((x) * 1000)
599 /** @brief Number of Hz in @p x MHz */
600 #define MHZ(x) (KHZ(x) * 1000)
601
602 /**
603 * @brief For the POSIX architecture add a minimal delay in a busy wait loop.
604 * For other architectures this is a no-op.
605 *
606 * In the POSIX ARCH, code takes zero simulated time to execute,
607 * so busy wait loops become infinite loops, unless we
608 * force the loop to take a bit of time.
609 * Include this macro in all busy wait/spin loops
610 * so they will also work when building for the POSIX architecture.
611 *
612 * @param t Time in microseconds we will busy wait
613 */
614 #if defined(CONFIG_ARCH_POSIX)
615 #define Z_SPIN_DELAY(t) k_busy_wait(t)
616 #else
617 #define Z_SPIN_DELAY(t)
618 #endif
619
620 /**
621 * @brief Wait for an expression to return true with a timeout
622 *
623 * Spin on an expression with a timeout and optional delay between iterations
624 *
625 * Commonly needed when waiting on hardware to complete an asynchronous
626 * request to read/write/initialize/reset, but useful for any expression.
627 *
628 * @param expr Truth expression upon which to poll, e.g.: XYZREG & XYZREG_EN
629 * @param timeout Timeout to wait for in microseconds, e.g.: 1000 (1ms)
630 * @param delay_stmt Delay statement to perform each poll iteration
631 * e.g.: NULL, k_yield(), k_msleep(1) or k_busy_wait(1)
632 *
633 * @retval expr As a boolean return, if false then it has timed out.
634 */
635 #define WAIT_FOR(expr, timeout, delay_stmt) \
636 ({ \
637 uint32_t cycle_count = k_us_to_cyc_ceil32(timeout); \
638 uint32_t start = k_cycle_get_32(); \
639 while (!(expr) && (cycle_count > (k_cycle_get_32() - start))) { \
640 delay_stmt; \
641 Z_SPIN_DELAY(10); \
642 } \
643 (expr); \
644 })
645
646 /**
647 * @}
648 */
649
650 #endif /* ZEPHYR_INCLUDE_SYS_UTIL_H_ */
651