eal: add functions for previous power of 2 alignment
[dpdk.git] / lib / librte_eal / common / include / rte_common.h
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4
5 #ifndef _RTE_COMMON_H_
6 #define _RTE_COMMON_H_
7
8 /**
9  * @file
10  *
11  * Generic, commonly-used macro and inline function definitions
12  * for DPDK.
13  */
14
15 #ifdef __cplusplus
16 extern "C" {
17 #endif
18
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <limits.h>
24
25 #include <rte_config.h>
26
27 #ifndef typeof
28 #define typeof __typeof__
29 #endif
30
31 #ifndef asm
32 #define asm __asm__
33 #endif
34
35 /** C extension macro for environments lacking C11 features. */
36 #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 201112L
37 #define RTE_STD_C11 __extension__
38 #else
39 #define RTE_STD_C11
40 #endif
41
42 /** Define GCC_VERSION **/
43 #ifdef RTE_TOOLCHAIN_GCC
44 #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 +  \
45                 __GNUC_PATCHLEVEL__)
46 #endif
47
48 #ifdef RTE_ARCH_STRICT_ALIGN
49 typedef uint64_t unaligned_uint64_t __attribute__ ((aligned(1)));
50 typedef uint32_t unaligned_uint32_t __attribute__ ((aligned(1)));
51 typedef uint16_t unaligned_uint16_t __attribute__ ((aligned(1)));
52 #else
53 typedef uint64_t unaligned_uint64_t;
54 typedef uint32_t unaligned_uint32_t;
55 typedef uint16_t unaligned_uint16_t;
56 #endif
57
58 /**
59  * Force alignment
60  */
61 #define __rte_aligned(a) __attribute__((__aligned__(a)))
62
63 /**
64  * Force a structure to be packed
65  */
66 #define __rte_packed __attribute__((__packed__))
67
68 /******* Macro to mark functions and fields scheduled for removal *****/
69 #define __rte_deprecated        __attribute__((__deprecated__))
70
71 /*********** Macros to eliminate unused variable warnings ********/
72
73 /**
74  * short definition to mark a function parameter unused
75  */
76 #define __rte_unused __attribute__((__unused__))
77
78 /**
79  * definition to mark a variable or function parameter as used so
80  * as to avoid a compiler warning
81  */
82 #define RTE_SET_USED(x) (void)(x)
83
84 /**
85  * Run function before main() with low priority.
86  *
87  * The constructor will be run after prioritized constructors.
88  *
89  * @param func
90  *   Constructor function.
91  */
92 #define RTE_INIT(func) \
93 static void __attribute__((constructor, used)) func(void)
94
95 /**
96  * Run function before main() with high priority.
97  *
98  * @param func
99  *   Constructor function.
100  * @param prio
101  *   Priority number must be above 100.
102  *   Lowest number is the first to run.
103  */
104 #define RTE_INIT_PRIO(func, prio) \
105 static void __attribute__((constructor(prio), used)) func(void)
106
107 /**
108  * Force a function to be inlined
109  */
110 #define __rte_always_inline inline __attribute__((always_inline))
111
112 /**
113  * Force a function to be noinlined
114  */
115 #define __rte_noinline  __attribute__((noinline))
116
117 /*********** Macros for pointer arithmetic ********/
118
119 /**
120  * add a byte-value offset from a pointer
121  */
122 #define RTE_PTR_ADD(ptr, x) ((void*)((uintptr_t)(ptr) + (x)))
123
124 /**
125  * subtract a byte-value offset from a pointer
126  */
127 #define RTE_PTR_SUB(ptr, x) ((void*)((uintptr_t)ptr - (x)))
128
129 /**
130  * get the difference between two pointer values, i.e. how far apart
131  * in bytes are the locations they point two. It is assumed that
132  * ptr1 is greater than ptr2.
133  */
134 #define RTE_PTR_DIFF(ptr1, ptr2) ((uintptr_t)(ptr1) - (uintptr_t)(ptr2))
135
136 /*********** Macros/static functions for doing alignment ********/
137
138
139 /**
140  * Macro to align a pointer to a given power-of-two. The resultant
141  * pointer will be a pointer of the same type as the first parameter, and
142  * point to an address no higher than the first parameter. Second parameter
143  * must be a power-of-two value.
144  */
145 #define RTE_PTR_ALIGN_FLOOR(ptr, align) \
146         ((typeof(ptr))RTE_ALIGN_FLOOR((uintptr_t)ptr, align))
147
148 /**
149  * Macro to align a value to a given power-of-two. The resultant value
150  * will be of the same type as the first parameter, and will be no
151  * bigger than the first parameter. Second parameter must be a
152  * power-of-two value.
153  */
154 #define RTE_ALIGN_FLOOR(val, align) \
155         (typeof(val))((val) & (~((typeof(val))((align) - 1))))
156
157 /**
158  * Macro to align a pointer to a given power-of-two. The resultant
159  * pointer will be a pointer of the same type as the first parameter, and
160  * point to an address no lower than the first parameter. Second parameter
161  * must be a power-of-two value.
162  */
163 #define RTE_PTR_ALIGN_CEIL(ptr, align) \
164         RTE_PTR_ALIGN_FLOOR((typeof(ptr))RTE_PTR_ADD(ptr, (align) - 1), align)
165
166 /**
167  * Macro to align a value to a given power-of-two. The resultant value
168  * will be of the same type as the first parameter, and will be no lower
169  * than the first parameter. Second parameter must be a power-of-two
170  * value.
171  */
172 #define RTE_ALIGN_CEIL(val, align) \
173         RTE_ALIGN_FLOOR(((val) + ((typeof(val)) (align) - 1)), align)
174
175 /**
176  * Macro to align a pointer to a given power-of-two. The resultant
177  * pointer will be a pointer of the same type as the first parameter, and
178  * point to an address no lower than the first parameter. Second parameter
179  * must be a power-of-two value.
180  * This function is the same as RTE_PTR_ALIGN_CEIL
181  */
182 #define RTE_PTR_ALIGN(ptr, align) RTE_PTR_ALIGN_CEIL(ptr, align)
183
184 /**
185  * Macro to align a value to a given power-of-two. The resultant
186  * value will be of the same type as the first parameter, and
187  * will be no lower than the first parameter. Second parameter
188  * must be a power-of-two value.
189  * This function is the same as RTE_ALIGN_CEIL
190  */
191 #define RTE_ALIGN(val, align) RTE_ALIGN_CEIL(val, align)
192
193 /**
194  * Macro to align a value to the multiple of given value. The resultant
195  * value will be of the same type as the first parameter and will be no lower
196  * than the first parameter.
197  */
198 #define RTE_ALIGN_MUL_CEIL(v, mul) \
199         (((v + (typeof(v))(mul) - 1) / ((typeof(v))(mul))) * (typeof(v))(mul))
200
201 /**
202  * Macro to align a value to the multiple of given value. The resultant
203  * value will be of the same type as the first parameter and will be no higher
204  * than the first parameter.
205  */
206 #define RTE_ALIGN_MUL_FLOOR(v, mul) \
207         ((v / ((typeof(v))(mul))) * (typeof(v))(mul))
208
209 /**
210  * Checks if a pointer is aligned to a given power-of-two value
211  *
212  * @param ptr
213  *   The pointer whose alignment is to be checked
214  * @param align
215  *   The power-of-two value to which the ptr should be aligned
216  *
217  * @return
218  *   True(1) where the pointer is correctly aligned, false(0) otherwise
219  */
220 static inline int
221 rte_is_aligned(void *ptr, unsigned align)
222 {
223         return RTE_PTR_ALIGN(ptr, align) == ptr;
224 }
225
226 /*********** Macros for compile type checks ********/
227
228 /**
229  * Triggers an error at compilation time if the condition is true.
230  */
231 #ifndef __OPTIMIZE__
232 #define RTE_BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
233 #else
234 extern int RTE_BUILD_BUG_ON_detected_error;
235 #define RTE_BUILD_BUG_ON(condition) do {             \
236         ((void)sizeof(char[1 - 2*!!(condition)]));   \
237         if (condition)                               \
238                 RTE_BUILD_BUG_ON_detected_error = 1; \
239 } while(0)
240 #endif
241
242 /**
243  * Combines 32b inputs most significant set bits into the least
244  * significant bits to construct a value with the same MSBs as x
245  * but all 1's under it.
246  *
247  * @param x
248  *    The integer whose MSBs need to be combined with its LSBs
249  * @return
250  *    The combined value.
251  */
252 static inline uint32_t
253 rte_combine32ms1b(register uint32_t x)
254 {
255         x |= x >> 1;
256         x |= x >> 2;
257         x |= x >> 4;
258         x |= x >> 8;
259         x |= x >> 16;
260
261         return x;
262 }
263
264 /**
265  * Combines 64b inputs most significant set bits into the least
266  * significant bits to construct a value with the same MSBs as x
267  * but all 1's under it.
268  *
269  * @param v
270  *    The integer whose MSBs need to be combined with its LSBs
271  * @return
272  *    The combined value.
273  */
274 static inline uint64_t
275 rte_combine64ms1b(register uint64_t v)
276 {
277         v |= v >> 1;
278         v |= v >> 2;
279         v |= v >> 4;
280         v |= v >> 8;
281         v |= v >> 16;
282         v |= v >> 32;
283
284         return v;
285 }
286
287 /*********** Macros to work with powers of 2 ********/
288
289 /**
290  * Returns true if n is a power of 2
291  * @param n
292  *     Number to check
293  * @return 1 if true, 0 otherwise
294  */
295 static inline int
296 rte_is_power_of_2(uint32_t n)
297 {
298         return n && !(n & (n - 1));
299 }
300
301 /**
302  * Aligns input parameter to the next power of 2
303  *
304  * @param x
305  *   The integer value to algin
306  *
307  * @return
308  *   Input parameter aligned to the next power of 2
309  */
310 static inline uint32_t
311 rte_align32pow2(uint32_t x)
312 {
313         x--;
314         x = rte_combine32ms1b(x);
315
316         return x + 1;
317 }
318
319 /**
320  * Aligns input parameter to the previous power of 2
321  *
322  * @param x
323  *   The integer value to algin
324  *
325  * @return
326  *   Input parameter aligned to the previous power of 2
327  */
328 static inline uint32_t
329 rte_align32prevpow2(uint32_t x)
330 {
331         x = rte_combine32ms1b(x);
332
333         return x - (x >> 1);
334 }
335
336 /**
337  * Aligns 64b input parameter to the next power of 2
338  *
339  * @param v
340  *   The 64b value to align
341  *
342  * @return
343  *   Input parameter aligned to the next power of 2
344  */
345 static inline uint64_t
346 rte_align64pow2(uint64_t v)
347 {
348         v--;
349         v = rte_combine64ms1b(v);
350
351         return v + 1;
352 }
353
354 /**
355  * Aligns 64b input parameter to the previous power of 2
356  *
357  * @param v
358  *   The 64b value to align
359  *
360  * @return
361  *   Input parameter aligned to the previous power of 2
362  */
363 static inline uint64_t
364 rte_align64prevpow2(uint64_t v)
365 {
366         v = rte_combine64ms1b(v);
367
368         return v - (v >> 1);
369 }
370
371 /*********** Macros for calculating min and max **********/
372
373 /**
374  * Macro to return the minimum of two numbers
375  */
376 #define RTE_MIN(a, b) \
377         __extension__ ({ \
378                 typeof (a) _a = (a); \
379                 typeof (b) _b = (b); \
380                 _a < _b ? _a : _b; \
381         })
382
383 /**
384  * Macro to return the maximum of two numbers
385  */
386 #define RTE_MAX(a, b) \
387         __extension__ ({ \
388                 typeof (a) _a = (a); \
389                 typeof (b) _b = (b); \
390                 _a > _b ? _a : _b; \
391         })
392
393 /*********** Other general functions / macros ********/
394
395 /**
396  * Searches the input parameter for the least significant set bit
397  * (starting from zero).
398  * If a least significant 1 bit is found, its bit index is returned.
399  * If the content of the input parameter is zero, then the content of the return
400  * value is undefined.
401  * @param v
402  *     input parameter, should not be zero.
403  * @return
404  *     least significant set bit in the input parameter.
405  */
406 static inline uint32_t
407 rte_bsf32(uint32_t v)
408 {
409         return __builtin_ctz(v);
410 }
411
412 /**
413  * Return the rounded-up log2 of a integer.
414  *
415  * @param v
416  *     The input parameter.
417  * @return
418  *     The rounded-up log2 of the input, or 0 if the input is 0.
419  */
420 static inline uint32_t
421 rte_log2_u32(uint32_t v)
422 {
423         if (v == 0)
424                 return 0;
425         v = rte_align32pow2(v);
426         return rte_bsf32(v);
427 }
428
429 #ifndef offsetof
430 /** Return the offset of a field in a structure. */
431 #define offsetof(TYPE, MEMBER)  __builtin_offsetof (TYPE, MEMBER)
432 #endif
433
434 /**
435  * Return pointer to the wrapping struct instance.
436  *
437  * Example:
438  *
439  *  struct wrapper {
440  *      ...
441  *      struct child c;
442  *      ...
443  *  };
444  *
445  *  struct child *x = obtain(...);
446  *  struct wrapper *w = container_of(x, struct wrapper, c);
447  */
448 #ifndef container_of
449 #define container_of(ptr, type, member) __extension__ ({                \
450                         const typeof(((type *)0)->member) *_ptr = (ptr); \
451                         __attribute__((unused)) type *_target_ptr =     \
452                                 (type *)(ptr);                          \
453                         (type *)(((uintptr_t)_ptr) - offsetof(type, member)); \
454                 })
455 #endif
456
457 #define _RTE_STR(x) #x
458 /** Take a macro value and get a string version of it */
459 #define RTE_STR(x) _RTE_STR(x)
460
461 /**
462  * ISO C helpers to modify format strings using variadic macros.
463  * This is a replacement for the ", ## __VA_ARGS__" GNU extension.
464  * An empty %s argument is appended to avoid a dangling comma.
465  */
466 #define RTE_FMT(fmt, ...) fmt "%.0s", __VA_ARGS__ ""
467 #define RTE_FMT_HEAD(fmt, ...) fmt
468 #define RTE_FMT_TAIL(fmt, ...) __VA_ARGS__
469
470 /** Mask value of type "tp" for the first "ln" bit set. */
471 #define RTE_LEN2MASK(ln, tp)    \
472         ((tp)((uint64_t)-1 >> (sizeof(uint64_t) * CHAR_BIT - (ln))))
473
474 /** Number of elements in the array. */
475 #define RTE_DIM(a)      (sizeof (a) / sizeof ((a)[0]))
476
477 /**
478  * Converts a numeric string to the equivalent uint64_t value.
479  * As well as straight number conversion, also recognises the suffixes
480  * k, m and g for kilobytes, megabytes and gigabytes respectively.
481  *
482  * If a negative number is passed in  i.e. a string with the first non-black
483  * character being "-", zero is returned. Zero is also returned in the case of
484  * an error with the strtoull call in the function.
485  *
486  * @param str
487  *     String containing number to convert.
488  * @return
489  *     Number.
490  */
491 static inline uint64_t
492 rte_str_to_size(const char *str)
493 {
494         char *endptr;
495         unsigned long long size;
496
497         while (isspace((int)*str))
498                 str++;
499         if (*str == '-')
500                 return 0;
501
502         errno = 0;
503         size = strtoull(str, &endptr, 0);
504         if (errno)
505                 return 0;
506
507         if (*endptr == ' ')
508                 endptr++; /* allow 1 space gap */
509
510         switch (*endptr){
511         case 'G': case 'g': size *= 1024; /* fall-through */
512         case 'M': case 'm': size *= 1024; /* fall-through */
513         case 'K': case 'k': size *= 1024; /* fall-through */
514         default:
515                 break;
516         }
517         return size;
518 }
519
520 /**
521  * Function to terminate the application immediately, printing an error
522  * message and returning the exit_code back to the shell.
523  *
524  * This function never returns
525  *
526  * @param exit_code
527  *     The exit code to be returned by the application
528  * @param format
529  *     The format string to be used for printing the message. This can include
530  *     printf format characters which will be expanded using any further parameters
531  *     to the function.
532  */
533 void
534 rte_exit(int exit_code, const char *format, ...)
535         __attribute__((noreturn))
536         __attribute__((format(printf, 2, 3)));
537
538 #ifdef __cplusplus
539 }
540 #endif
541
542 #endif