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 <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 #include <stdint.h>
29
30 #ifdef __cplusplus
31 extern "C" {
32 #endif
33
34 /**
35 * @defgroup sys-util Utility Functions
36 * @{
37 */
38
39 /** @brief Cast @p x, a pointer, to an unsigned integer. */
40 #define POINTER_TO_UINT(x) ((uintptr_t) (x))
41 /** @brief Cast @p x, an unsigned integer, to a <tt>void*</tt>. */
42 #define UINT_TO_POINTER(x) ((void *) (uintptr_t) (x))
43 /** @brief Cast @p x, a pointer, to a signed integer. */
44 #define POINTER_TO_INT(x) ((intptr_t) (x))
45 /** @brief Cast @p x, a signed integer, to a <tt>void*</tt>. */
46 #define INT_TO_POINTER(x) ((void *) (intptr_t) (x))
47
48 #if !(defined(__CHAR_BIT__) && defined(__SIZEOF_LONG__))
49 # error Missing required predefined macros for BITS_PER_LONG calculation
50 #endif
51
52 /** Number of bits in a long int. */
53 #define BITS_PER_LONG (__CHAR_BIT__ * __SIZEOF_LONG__)
54
55 /**
56 * @brief Create a contiguous bitmask starting at bit position @p l
57 * and ending at position @p h.
58 */
59 #define GENMASK(h, l) \
60 (((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
61
62 /** @brief 0 if @p cond is true-ish; causes a compile error otherwise. */
63 #define ZERO_OR_COMPILE_ERROR(cond) ((int) sizeof(char[1 - 2 * !(cond)]) - 1)
64
65 /**
66 * @brief Determine if a buffer exceeds highest address
67 *
68 * This macro determines if a buffer identified by a starting address @a addr
69 * and length @a buflen spans a region of memory that goes beond the highest
70 * possible address (thereby resulting in a pointer overflow).
71 *
72 * @param addr Buffer starting address
73 * @param buflen Length of the buffer
74 *
75 * @return true if pointer overflow detected, false otherwise
76 */
77 #define Z_DETECT_POINTER_OVERFLOW(addr, buflen) \
78 (((buflen) != 0) && \
79 ((UINTPTR_MAX - (uintptr_t)(addr)) <= ((uintptr_t)((buflen) - 1))))
80
81
82 #if defined(__cplusplus)
83
84 /* The built-in function used below for type checking in C is not
85 * supported by GNU C++.
86 */
87 #define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
88
89 #else /* __cplusplus */
90
91 /**
92 * @brief Zero if @p array has an array type, a compile error otherwise
93 *
94 * This macro is available only from C, not C++.
95 */
96 #define IS_ARRAY(array) \
97 ZERO_OR_COMPILE_ERROR( \
98 !__builtin_types_compatible_p(__typeof__(array), \
99 __typeof__(&(array)[0])))
100
101 /**
102 * @brief Number of elements in the given @p array
103 *
104 * In C++, due to language limitations, this will accept as @p array
105 * any type that implements <tt>operator[]</tt>. The results may not be
106 * particulary meaningful in this case.
107 *
108 * In C, passing a pointer as @p array causes a compile error.
109 */
110 #define ARRAY_SIZE(array) \
111 ((long) (IS_ARRAY(array) + (sizeof(array) / sizeof((array)[0]))))
112
113 #endif /* __cplusplus */
114
115 /**
116 * @brief Check if a pointer @p ptr lies within @p array.
117 *
118 * In C but not C++, this causes a compile error if @p array is not an array
119 * (e.g. if @p ptr and @p array are mixed up).
120 *
121 * @param ptr a pointer
122 * @param array an array
123 * @return 1 if @p ptr is part of @p array, 0 otherwise
124 */
125 #define PART_OF_ARRAY(array, ptr) \
126 ((ptr) && ((ptr) >= &array[0] && (ptr) < &array[ARRAY_SIZE(array)]))
127
128 /**
129 * @brief Get a pointer to a container structure from an element
130 *
131 * Example:
132 *
133 * struct foo {
134 * int bar;
135 * };
136 *
137 * struct foo my_foo;
138 * int *ptr = &my_foo.bar;
139 *
140 * struct foo *container = CONTAINER_OF(ptr, struct foo, bar);
141 *
142 * Above, @p container points at @p my_foo.
143 *
144 * @param ptr pointer to a structure element
145 * @param type name of the type that @p ptr is an element of
146 * @param field the name of the field within the struct @p ptr points to
147 * @return a pointer to the structure that contains @p ptr
148 */
149 #define CONTAINER_OF(ptr, type, field) \
150 ((type *)(((char *)(ptr)) - offsetof(type, field)))
151
152 /**
153 * @brief Value of @p x rounded up to the next multiple of @p align,
154 * which must be a power of 2.
155 */
156 #define ROUND_UP(x, align) \
157 (((unsigned long)(x) + ((unsigned long)(align) - 1)) & \
158 ~((unsigned long)(align) - 1))
159
160 /**
161 * @brief Value of @p x rounded down to the previous multiple of @p
162 * align, which must be a power of 2.
163 */
164 #define ROUND_DOWN(x, align) \
165 ((unsigned long)(x) & ~((unsigned long)(align) - 1))
166
167 /** @brief Value of @p x rounded up to the next word boundary. */
168 #define WB_UP(x) ROUND_UP(x, sizeof(void *))
169
170 /** @brief Value of @p x rounded down to the previous word boundary. */
171 #define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
172
173 /**
174 * @brief Ceiling function applied to @p numerator / @p divider as a fraction.
175 */
176 #define ceiling_fraction(numerator, divider) \
177 (((numerator) + ((divider) - 1)) / (divider))
178
179 /**
180 * @def MAX
181 * @brief The larger value between @p a and @p b.
182 * @note Arguments are evaluated twice.
183 */
184 #ifndef MAX
185 /* Use Z_MAX for a GCC-only, single evaluation version */
186 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
187 #endif
188
189 /**
190 * @def MIN
191 * @brief The smaller value between @p a and @p b.
192 * @note Arguments are evaluated twice.
193 */
194 #ifndef MIN
195 /* Use Z_MIN for a GCC-only, single evaluation version */
196 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
197 #endif
198
199 /**
200 * @def CLAMP
201 * @brief Clamp a value to a given range.
202 * @note Arguments are evaluated multiple times.
203 */
204 #ifndef CLAMP
205 /* Use Z_CLAMP for a GCC-only, single evaluation version */
206 #define CLAMP(val, low, high) (((val) <= (low)) ? (low) : MIN(val, high))
207 #endif
208
209 /**
210 * @brief Is @p x a power of two?
211 * @param x value to check
212 * @return true if @p x is a power of two, false otherwise
213 */
is_power_of_two(unsigned int x)214 static inline bool is_power_of_two(unsigned int x)
215 {
216 return (x != 0U) && ((x & (x - 1U)) == 0U);
217 }
218
219 /**
220 * @brief Arithmetic shift right
221 * @param value value to shift
222 * @param shift number of bits to shift
223 * @return @p value shifted right by @p shift; opened bit positions are
224 * filled with the sign bit
225 */
arithmetic_shift_right(int64_t value,uint8_t shift)226 static inline int64_t arithmetic_shift_right(int64_t value, uint8_t shift)
227 {
228 int64_t sign_ext;
229
230 if (shift == 0U) {
231 return value;
232 }
233
234 /* extract sign bit */
235 sign_ext = (value >> 63) & 1;
236
237 /* make all bits of sign_ext be the same as the value's sign bit */
238 sign_ext = -sign_ext;
239
240 /* shift value and fill opened bit positions with sign bit */
241 return (value >> shift) | (sign_ext << (64 - shift));
242 }
243
244 /**
245 * @brief byte by byte memcpy.
246 *
247 * Copy `size` bytes of `src` into `dest`. This is guaranteed to be done byte by byte.
248 *
249 * @param dst Pointer to the destination memory.
250 * @param src Pointer to the source of the data.
251 * @param size The number of bytes to copy.
252 */
bytecpy(void * dst,const void * src,size_t size)253 static inline void bytecpy(void *dst, const void *src, size_t size)
254 {
255 size_t i;
256
257 for (i = 0; i < size; ++i) {
258 ((uint8_t *)dst)[i] = ((uint8_t *)src)[i];
259 }
260 }
261
262 /**
263 * @brief byte by byte swap.
264 *
265 * Swap @a size bytes between memory regions @a a and @a b. This is
266 * guaranteed to be done byte by byte.
267 *
268 * @param a Pointer to the the first memory region.
269 * @param b Pointer to the the second memory region.
270 * @param size The number of bytes to swap.
271 */
byteswp(void * a,void * b,size_t size)272 static inline void byteswp(void *a, void *b, size_t size)
273 {
274 uint8_t t;
275 uint8_t *aa = (uint8_t *)a;
276 uint8_t *bb = (uint8_t *)b;
277
278 for (; size > 0; --size) {
279 t = *aa;
280 *aa++ = *bb;
281 *bb++ = t;
282 }
283 }
284
285 /**
286 * @brief Convert a single character into a hexadecimal nibble.
287 *
288 * @param c The character to convert
289 * @param x The address of storage for the converted number.
290 *
291 * @return Zero on success or (negative) error code otherwise.
292 */
293 int char2hex(char c, uint8_t *x);
294
295 /**
296 * @brief Convert a single hexadecimal nibble into a character.
297 *
298 * @param c The number to convert
299 * @param x The address of storage for the converted character.
300 *
301 * @return Zero on success or (negative) error code otherwise.
302 */
303 int hex2char(uint8_t x, char *c);
304
305 /**
306 * @brief Convert a binary array into string representation.
307 *
308 * @param buf The binary array to convert
309 * @param buflen The length of the binary array to convert
310 * @param hex Address of where to store the string representation.
311 * @param hexlen Size of the storage area for string representation.
312 *
313 * @return The length of the converted string, or 0 if an error occurred.
314 */
315 size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
316
317 /**
318 * @brief Convert a hexadecimal string into a binary array.
319 *
320 * @param hex The hexadecimal string to convert
321 * @param hexlen The length of the hexadecimal string to convert.
322 * @param buf Address of where to store the binary data
323 * @param buflen Size of the storage area for binary data
324 *
325 * @return The length of the binary array, or 0 if an error occurred.
326 */
327 size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
328
329 /**
330 * @brief Convert a binary coded decimal (BCD 8421) value to binary.
331 *
332 * @param bcd BCD 8421 value to convert.
333 *
334 * @return Binary representation of input value.
335 */
bcd2bin(uint8_t bcd)336 static inline uint8_t bcd2bin(uint8_t bcd)
337 {
338 return ((10 * (bcd >> 4)) + (bcd & 0x0F));
339 }
340
341 /**
342 * @brief Convert a binary value to binary coded decimal (BCD 8421).
343 *
344 * @param bin Binary value to convert.
345 *
346 * @return BCD 8421 representation of input value.
347 */
bin2bcd(uint8_t bin)348 static inline uint8_t bin2bcd(uint8_t bin)
349 {
350 return (((bin / 10) << 4) | (bin % 10));
351 }
352
353 /**
354 * @brief Convert a uint8_t into a decimal string representation.
355 *
356 * Convert a uint8_t value into its ASCII decimal string representation.
357 * The string is terminated if there is enough space in buf.
358 *
359 * @param buf Address of where to store the string representation.
360 * @param buflen Size of the storage area for string representation.
361 * @param value The value to convert to decimal string
362 *
363 * @return The length of the converted string (excluding terminator if
364 * any), or 0 if an error occurred.
365 */
366 uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value);
367
368 #ifdef __cplusplus
369 }
370 #endif
371
372 #endif /* !_ASMLANGUAGE */
373
374 /** @brief Number of bytes in @p x kibibytes */
375 #ifdef _LINKER
376 /* This is used in linker scripts so need to avoid type casting there */
377 #define KB(x) ((x) << 10)
378 #else
379 #define KB(x) (((size_t)x) << 10)
380 #endif
381 /** @brief Number of bytes in @p x mebibytes */
382 #define MB(x) (KB(x) << 10)
383 /** @brief Number of bytes in @p x gibibytes */
384 #define GB(x) (MB(x) << 10)
385
386 /** @brief Number of Hz in @p x kHz */
387 #define KHZ(x) ((x) * 1000)
388 /** @brief Number of Hz in @p x MHz */
389 #define MHZ(x) (KHZ(x) * 1000)
390
391 /**
392 * @}
393 */
394
395 #endif /* ZEPHYR_INCLUDE_SYS_UTIL_H_ */
396