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