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 Validate if two entities have a compatible type
207  *
208  * @param a the first entity to be compared
209  * @param b the second entity to be compared
210  * @return 1 if the two elements are compatible, 0 if they are not
211  */
212 #define SAME_TYPE(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
213 
214 /**
215  * @brief Validate CONTAINER_OF parameters, only applies to C mode.
216  */
217 #ifndef __cplusplus
218 #define CONTAINER_OF_VALIDATE(ptr, type, field)               \
219 	BUILD_ASSERT(SAME_TYPE(*(ptr), ((type *)0)->field) || \
220 		     SAME_TYPE(*(ptr), void),                 \
221 		     "pointer type mismatch in CONTAINER_OF");
222 #else
223 #define CONTAINER_OF_VALIDATE(ptr, type, field)
224 #endif
225 
226 /**
227  * @brief Get a pointer to a structure containing the element
228  *
229  * Example:
230  *
231  *	struct foo {
232  *		int bar;
233  *	};
234  *
235  *	struct foo my_foo;
236  *	int *ptr = &my_foo.bar;
237  *
238  *	struct foo *container = CONTAINER_OF(ptr, struct foo, bar);
239  *
240  * Above, @p container points at @p my_foo.
241  *
242  * @param ptr pointer to a structure element
243  * @param type name of the type that @p ptr is an element of
244  * @param field the name of the field within the struct @p ptr points to
245  * @return a pointer to the structure that contains @p ptr
246  */
247 #define CONTAINER_OF(ptr, type, field)                               \
248 	({                                                           \
249 		CONTAINER_OF_VALIDATE(ptr, type, field)              \
250 		((type *)(((char *)(ptr)) - offsetof(type, field))); \
251 	})
252 
253 /**
254  * @brief Value of @p x rounded up to the next multiple of @p align.
255  */
256 #define ROUND_UP(x, align)                                   \
257 	((((unsigned long)(x) + ((unsigned long)(align) - 1)) / \
258 	  (unsigned long)(align)) * (unsigned long)(align))
259 
260 /**
261  * @brief Value of @p x rounded down to the previous multiple of @p align.
262  */
263 #define ROUND_DOWN(x, align)                                 \
264 	(((unsigned long)(x) / (unsigned long)(align)) * (unsigned long)(align))
265 
266 /** @brief Value of @p x rounded up to the next word boundary. */
267 #define WB_UP(x) ROUND_UP(x, sizeof(void *))
268 
269 /** @brief Value of @p x rounded down to the previous word boundary. */
270 #define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
271 
272 /**
273  * @brief Divide and round up.
274  *
275  * Example:
276  * @code{.c}
277  * DIV_ROUND_UP(1, 2); // 1
278  * DIV_ROUND_UP(3, 2); // 2
279  * @endcode
280  *
281  * @param n Numerator.
282  * @param d Denominator.
283  *
284  * @return The result of @p n / @p d, rounded up.
285  */
286 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
287 
288 /**
289  * @brief Divide and round to the nearest integer.
290  *
291  * Example:
292  * @code{.c}
293  * DIV_ROUND_CLOSEST(5, 2); // 3
294  * DIV_ROUND_CLOSEST(5, -2); // -3
295  * DIV_ROUND_CLOSEST(5, 3); // 2
296  * @endcode
297  *
298  * @param n Numerator.
299  * @param d Denominator.
300  *
301  * @return The result of @p n / @p d, rounded to the nearest integer.
302  */
303 #define DIV_ROUND_CLOSEST(n, d)	\
304 	((((n) < 0) ^ ((d) < 0)) ? ((n) - ((d) / 2)) / (d) : \
305 	((n) + ((d) / 2)) / (d))
306 
307 /**
308  * @brief Ceiling function applied to @p numerator / @p divider as a fraction.
309  * @deprecated Use DIV_ROUND_UP() instead.
310  */
311 #define ceiling_fraction(numerator, divider) __DEPRECATED_MACRO \
312 	DIV_ROUND_UP(numerator, divider)
313 
314 #ifndef MAX
315 /**
316  * @brief Obtain the maximum of two values.
317  *
318  * @note Arguments are evaluated twice. Use Z_MAX for a GCC-only, single
319  * evaluation version
320  *
321  * @param a First value.
322  * @param b Second value.
323  *
324  * @returns Maximum value of @p a and @p b.
325  */
326 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
327 #endif
328 
329 #ifndef MIN
330 /**
331  * @brief Obtain the minimum of two values.
332  *
333  * @note Arguments are evaluated twice. Use Z_MIN for a GCC-only, single
334  * evaluation version
335  *
336  * @param a First value.
337  * @param b Second value.
338  *
339  * @returns Minimum value of @p a and @p b.
340  */
341 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
342 #endif
343 
344 #ifndef CLAMP
345 /**
346  * @brief Clamp a value to a given range.
347  *
348  * @note Arguments are evaluated multiple times. Use Z_CLAMP for a GCC-only,
349  * single evaluation version.
350  *
351  * @param val Value to be clamped.
352  * @param low Lowest allowed value (inclusive).
353  * @param high Highest allowed value (inclusive).
354  *
355  * @returns Clamped value.
356  */
357 #define CLAMP(val, low, high) (((val) <= (low)) ? (low) : MIN(val, high))
358 #endif
359 
360 /**
361  * @brief Checks if a value is within range.
362  *
363  * @note @p val is evaluated twice.
364  *
365  * @param val Value to be checked.
366  * @param min Lower bound (inclusive).
367  * @param max Upper bound (inclusive).
368  *
369  * @retval true If value is within range
370  * @retval false If the value is not within range
371  */
372 #define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
373 
374 /**
375  * @brief Is @p x a power of two?
376  * @param x value to check
377  * @return true if @p x is a power of two, false otherwise
378  */
is_power_of_two(unsigned int x)379 static inline bool is_power_of_two(unsigned int x)
380 {
381 	return IS_POWER_OF_TWO(x);
382 }
383 
384 /**
385  * @brief Arithmetic shift right
386  * @param value value to shift
387  * @param shift number of bits to shift
388  * @return @p value shifted right by @p shift; opened bit positions are
389  *         filled with the sign bit
390  */
arithmetic_shift_right(int64_t value,uint8_t shift)391 static inline int64_t arithmetic_shift_right(int64_t value, uint8_t shift)
392 {
393 	int64_t sign_ext;
394 
395 	if (shift == 0U) {
396 		return value;
397 	}
398 
399 	/* extract sign bit */
400 	sign_ext = (value >> 63) & 1;
401 
402 	/* make all bits of sign_ext be the same as the value's sign bit */
403 	sign_ext = -sign_ext;
404 
405 	/* shift value and fill opened bit positions with sign bit */
406 	return (value >> shift) | (sign_ext << (64 - shift));
407 }
408 
409 /**
410  * @brief byte by byte memcpy.
411  *
412  * Copy `size` bytes of `src` into `dest`. This is guaranteed to be done byte by byte.
413  *
414  * @param dst Pointer to the destination memory.
415  * @param src Pointer to the source of the data.
416  * @param size The number of bytes to copy.
417  */
bytecpy(void * dst,const void * src,size_t size)418 static inline void bytecpy(void *dst, const void *src, size_t size)
419 {
420 	size_t i;
421 
422 	for (i = 0; i < size; ++i) {
423 		((volatile uint8_t *)dst)[i] = ((volatile const uint8_t *)src)[i];
424 	}
425 }
426 
427 /**
428  * @brief byte by byte swap.
429  *
430  * Swap @a size bytes between memory regions @a a and @a b. This is
431  * guaranteed to be done byte by byte.
432  *
433  * @param a Pointer to the the first memory region.
434  * @param b Pointer to the the second memory region.
435  * @param size The number of bytes to swap.
436  */
byteswp(void * a,void * b,size_t size)437 static inline void byteswp(void *a, void *b, size_t size)
438 {
439 	uint8_t t;
440 	uint8_t *aa = (uint8_t *)a;
441 	uint8_t *bb = (uint8_t *)b;
442 
443 	for (; size > 0; --size) {
444 		t = *aa;
445 		*aa++ = *bb;
446 		*bb++ = t;
447 	}
448 }
449 
450 /**
451  * @brief      Convert a single character into a hexadecimal nibble.
452  *
453  * @param c     The character to convert
454  * @param x     The address of storage for the converted number.
455  *
456  *  @return Zero on success or (negative) error code otherwise.
457  */
458 int char2hex(char c, uint8_t *x);
459 
460 /**
461  * @brief      Convert a single hexadecimal nibble into a character.
462  *
463  * @param c     The number to convert
464  * @param x     The address of storage for the converted character.
465  *
466  *  @return Zero on success or (negative) error code otherwise.
467  */
468 int hex2char(uint8_t x, char *c);
469 
470 /**
471  * @brief      Convert a binary array into string representation.
472  *
473  * @param buf     The binary array to convert
474  * @param buflen  The length of the binary array to convert
475  * @param hex     Address of where to store the string representation.
476  * @param hexlen  Size of the storage area for string representation.
477  *
478  * @return     The length of the converted string, or 0 if an error occurred.
479  */
480 size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
481 
482 /**
483  * @brief      Convert a hexadecimal string into a binary array.
484  *
485  * @param hex     The hexadecimal string to convert
486  * @param hexlen  The length of the hexadecimal string to convert.
487  * @param buf     Address of where to store the binary data
488  * @param buflen  Size of the storage area for binary data
489  *
490  * @return     The length of the binary array, or 0 if an error occurred.
491  */
492 size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
493 
494 /**
495  * @brief Convert a binary coded decimal (BCD 8421) value to binary.
496  *
497  * @param bcd BCD 8421 value to convert.
498  *
499  * @return Binary representation of input value.
500  */
bcd2bin(uint8_t bcd)501 static inline uint8_t bcd2bin(uint8_t bcd)
502 {
503 	return ((10 * (bcd >> 4)) + (bcd & 0x0F));
504 }
505 
506 /**
507  * @brief Convert a binary value to binary coded decimal (BCD 8421).
508  *
509  * @param bin Binary value to convert.
510  *
511  * @return BCD 8421 representation of input value.
512  */
bin2bcd(uint8_t bin)513 static inline uint8_t bin2bcd(uint8_t bin)
514 {
515 	return (((bin / 10) << 4) | (bin % 10));
516 }
517 
518 /**
519  * @brief      Convert a uint8_t into a decimal string representation.
520  *
521  * Convert a uint8_t value into its ASCII decimal string representation.
522  * The string is terminated if there is enough space in buf.
523  *
524  * @param buf     Address of where to store the string representation.
525  * @param buflen  Size of the storage area for string representation.
526  * @param value   The value to convert to decimal string
527  *
528  * @return     The length of the converted string (excluding terminator if
529  *             any), or 0 if an error occurred.
530  */
531 uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);
532 
533 /**
534  * @brief Properly truncate a NULL-terminated UTF-8 string
535  *
536  * Take a NULL-terminated UTF-8 string and ensure that if the string has been
537  * truncated (by setting the NULL terminator) earlier by other means, that
538  * the string ends with a properly formatted UTF-8 character (1-4 bytes).
539  *
540  * @htmlonly
541  * Example:
542  *      char test_str[] = "€€€";
543  *      char trunc_utf8[8];
544  *
545  *      printf("Original : %s\n", test_str); // €€€
546  *      strncpy(trunc_utf8, test_str, sizeof(trunc_utf8));
547  *      trunc_utf8[sizeof(trunc_utf8) - 1] = '\0';
548  *      printf("Bad      : %s\n", trunc_utf8); // €€�
549  *      utf8_trunc(trunc_utf8);
550  *      printf("Truncated: %s\n", trunc_utf8); // €€
551  * @endhtmlonly
552  *
553  * @param utf8_str NULL-terminated string
554  *
555  * @return Pointer to the @p utf8_str
556  */
557 char *utf8_trunc(char *utf8_str);
558 
559 /**
560  * @brief Copies a UTF-8 encoded string from @p src to @p dst
561  *
562  * The resulting @p dst will always be NULL terminated if @p n is larger than 0,
563  * and the @p dst string will always be properly UTF-8 truncated.
564  *
565  * @param dst The destination of the UTF-8 string.
566  * @param src The source string
567  * @param n   The size of the @p dst buffer. Maximum number of characters copied
568  *            is @p n - 1. If 0 nothing will be done, and the @p dst will not be
569  *            NULL terminated.
570  *
571  * @return Pointer to the @p dst
572  */
573 char *utf8_lcpy(char *dst, const char *src, size_t n);
574 
575 #define __z_log2d(x) (32 - __builtin_clz(x) - 1)
576 #define __z_log2q(x) (64 - __builtin_clzll(x) - 1)
577 #define __z_log2(x) (sizeof(__typeof__(x)) > 4 ? __z_log2q(x) : __z_log2d(x))
578 
579 /**
580  * @brief Compute log2(x)
581  *
582  * @note This macro expands its argument multiple times (to permit use
583  *       in constant expressions), which must not have side effects.
584  *
585  * @param x An unsigned integral value to compute logarithm of (positive only)
586  *
587  * @return log2(x) when 1 <= x <= max(x), -1 when x < 1
588  */
589 #define LOG2(x) ((x) < 1 ? -1 : __z_log2(x))
590 
591 /**
592  * @brief Compute ceil(log2(x))
593  *
594  * @note This macro expands its argument multiple times (to permit use
595  *       in constant expressions), which must not have side effects.
596  *
597  * @param x An unsigned integral value
598  *
599  * @return ceil(log2(x)) when 1 <= x <= max(type(x)), 0 when x < 1
600  */
601 #define LOG2CEIL(x) ((x) < 1 ?  0 : __z_log2((x)-1) + 1)
602 
603 /**
604  * @brief Compute next highest power of two
605  *
606  * Equivalent to 2^ceil(log2(x))
607  *
608  * @note This macro expands its argument multiple times (to permit use
609  *       in constant expressions), which must not have side effects.
610  *
611  * @param x An unsigned integral value
612  *
613  * @return 2^ceil(log2(x)) or 0 if 2^ceil(log2(x)) would saturate 64-bits
614  */
615 #define NHPOT(x) ((x) < 1 ? 1 : ((x) > (1ULL<<63) ? 0 : 1ULL << LOG2CEIL(x)))
616 
617 /**
618  * @brief Determine if a buffer exceeds highest address
619  *
620  * This macro determines if a buffer identified by a starting address @a addr
621  * and length @a buflen spans a region of memory that goes beond the highest
622  * possible address (thereby resulting in a pointer overflow).
623  *
624  * @param addr Buffer starting address
625  * @param buflen Length of the buffer
626  *
627  * @return true if pointer overflow detected, false otherwise
628  */
629 #define Z_DETECT_POINTER_OVERFLOW(addr, buflen)  \
630 	(((buflen) != 0) &&                        \
631 	((UINTPTR_MAX - (uintptr_t)(addr)) <= ((uintptr_t)((buflen) - 1))))
632 
633 #ifdef __cplusplus
634 }
635 #endif
636 
637 /* This file must be included at the end of the !_ASMLANGUAGE guard.
638  * It depends on macros defined in this file above which cannot be forward declared.
639  */
640 #include <zephyr/sys/time_units.h>
641 
642 #endif /* !_ASMLANGUAGE */
643 
644 /** @brief Number of bytes in @p x kibibytes */
645 #ifdef _LINKER
646 /* This is used in linker scripts so need to avoid type casting there */
647 #define KB(x) ((x) << 10)
648 #else
649 #define KB(x) (((size_t)x) << 10)
650 #endif
651 /** @brief Number of bytes in @p x mebibytes */
652 #define MB(x) (KB(x) << 10)
653 /** @brief Number of bytes in @p x gibibytes */
654 #define GB(x) (MB(x) << 10)
655 
656 /** @brief Number of Hz in @p x kHz */
657 #define KHZ(x) ((x) * 1000)
658 /** @brief Number of Hz in @p x MHz */
659 #define MHZ(x) (KHZ(x) * 1000)
660 
661 /**
662  * @brief For the POSIX architecture add a minimal delay in a busy wait loop.
663  * For other architectures this is a no-op.
664  *
665  * In the POSIX ARCH, code takes zero simulated time to execute,
666  * so busy wait loops become infinite loops, unless we
667  * force the loop to take a bit of time.
668  * Include this macro in all busy wait/spin loops
669  * so they will also work when building for the POSIX architecture.
670  *
671  * @param t Time in microseconds we will busy wait
672  */
673 #if defined(CONFIG_ARCH_POSIX)
674 #define Z_SPIN_DELAY(t) k_busy_wait(t)
675 #else
676 #define Z_SPIN_DELAY(t)
677 #endif
678 
679 /**
680  * @brief Wait for an expression to return true with a timeout
681  *
682  * Spin on an expression with a timeout and optional delay between iterations
683  *
684  * Commonly needed when waiting on hardware to complete an asynchronous
685  * request to read/write/initialize/reset, but useful for any expression.
686  *
687  * @param expr Truth expression upon which to poll, e.g.: XYZREG & XYZREG_EN
688  * @param timeout Timeout to wait for in microseconds, e.g.: 1000 (1ms)
689  * @param delay_stmt Delay statement to perform each poll iteration
690  *                   e.g.: NULL, k_yield(), k_msleep(1) or k_busy_wait(1)
691  *
692  * @retval expr As a boolean return, if false then it has timed out.
693  */
694 #define WAIT_FOR(expr, timeout, delay_stmt)                                                        \
695 	({                                                                                         \
696 		uint32_t _wf_cycle_count = k_us_to_cyc_ceil32(timeout);                            \
697 		uint32_t _wf_start = k_cycle_get_32();                                             \
698 		while (!(expr) && (_wf_cycle_count > (k_cycle_get_32() - _wf_start))) {            \
699 			delay_stmt;                                                                \
700 			Z_SPIN_DELAY(10);                                                          \
701 		}                                                                                  \
702 		(expr);                                                                            \
703 	})
704 
705 /**
706  * @}
707  */
708 
709 #endif /* ZEPHYR_INCLUDE_SYS_UTIL_H_ */
710