eal: add macro to align value to the nearest multiple
[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 /**
72  * Mark a function or variable to a weak reference.
73  */
74 #define __rte_weak __attribute__((__weak__))
75
76 /*********** Macros to eliminate unused variable warnings ********/
77
78 /**
79  * short definition to mark a function parameter unused
80  */
81 #define __rte_unused __attribute__((__unused__))
82
83 /**
84  * definition to mark a variable or function parameter as used so
85  * as to avoid a compiler warning
86  */
87 #define RTE_SET_USED(x) (void)(x)
88
89 #define RTE_PRIORITY_LOG 101
90 #define RTE_PRIORITY_BUS 110
91 #define RTE_PRIORITY_CLASS 120
92 #define RTE_PRIORITY_LAST 65535
93
94 #define RTE_PRIO(prio) \
95         RTE_PRIORITY_ ## prio
96
97 /**
98  * Run function before main() with high priority.
99  *
100  * @param func
101  *   Constructor function.
102  * @param prio
103  *   Priority number must be above 100.
104  *   Lowest number is the first to run.
105  */
106 #define RTE_INIT_PRIO(func, prio) \
107 static void __attribute__((constructor(RTE_PRIO(prio)), used)) func(void)
108
109 /**
110  * Run function before main() with low priority.
111  *
112  * The constructor will be run after prioritized constructors.
113  *
114  * @param func
115  *   Constructor function.
116  */
117 #define RTE_INIT(func) \
118         RTE_INIT_PRIO(func, LAST)
119
120 /**
121  * Run after main() with low priority.
122  *
123  * @param func
124  *   Destructor function name.
125  * @param prio
126  *   Priority number must be above 100.
127  *   Lowest number is the last to run.
128  */
129 #define RTE_FINI_PRIO(func, prio) \
130 static void __attribute__((destructor(RTE_PRIO(prio)), used)) func(void)
131
132 /**
133  * Run after main() with high priority.
134  *
135  * The destructor will be run *before* prioritized destructors.
136  *
137  * @param func
138  *   Destructor function name.
139  */
140 #define RTE_FINI(func) \
141         RTE_FINI_PRIO(func, LAST)
142
143 /**
144  * Force a function to be inlined
145  */
146 #define __rte_always_inline inline __attribute__((always_inline))
147
148 /**
149  * Force a function to be noinlined
150  */
151 #define __rte_noinline  __attribute__((noinline))
152
153 /*********** Macros for pointer arithmetic ********/
154
155 /**
156  * add a byte-value offset to a pointer
157  */
158 #define RTE_PTR_ADD(ptr, x) ((void*)((uintptr_t)(ptr) + (x)))
159
160 /**
161  * subtract a byte-value offset from a pointer
162  */
163 #define RTE_PTR_SUB(ptr, x) ((void*)((uintptr_t)ptr - (x)))
164
165 /**
166  * get the difference between two pointer values, i.e. how far apart
167  * in bytes are the locations they point two. It is assumed that
168  * ptr1 is greater than ptr2.
169  */
170 #define RTE_PTR_DIFF(ptr1, ptr2) ((uintptr_t)(ptr1) - (uintptr_t)(ptr2))
171
172 /**
173  * Workaround to cast a const field of a structure to non-const type.
174  */
175 #define RTE_CAST_FIELD(var, field, type) \
176         (*(type *)((uintptr_t)(var) + offsetof(typeof(*(var)), field)))
177
178 /*********** Macros/static functions for doing alignment ********/
179
180
181 /**
182  * Macro to align a pointer to a given power-of-two. The resultant
183  * pointer will be a pointer of the same type as the first parameter, and
184  * point to an address no higher than the first parameter. Second parameter
185  * must be a power-of-two value.
186  */
187 #define RTE_PTR_ALIGN_FLOOR(ptr, align) \
188         ((typeof(ptr))RTE_ALIGN_FLOOR((uintptr_t)ptr, align))
189
190 /**
191  * Macro to align a value to a given power-of-two. The resultant value
192  * will be of the same type as the first parameter, and will be no
193  * bigger than the first parameter. Second parameter must be a
194  * power-of-two value.
195  */
196 #define RTE_ALIGN_FLOOR(val, align) \
197         (typeof(val))((val) & (~((typeof(val))((align) - 1))))
198
199 /**
200  * Macro to align a pointer to a given power-of-two. The resultant
201  * pointer will be a pointer of the same type as the first parameter, and
202  * point to an address no lower than the first parameter. Second parameter
203  * must be a power-of-two value.
204  */
205 #define RTE_PTR_ALIGN_CEIL(ptr, align) \
206         RTE_PTR_ALIGN_FLOOR((typeof(ptr))RTE_PTR_ADD(ptr, (align) - 1), align)
207
208 /**
209  * Macro to align a value to a given power-of-two. The resultant value
210  * will be of the same type as the first parameter, and will be no lower
211  * than the first parameter. Second parameter must be a power-of-two
212  * value.
213  */
214 #define RTE_ALIGN_CEIL(val, align) \
215         RTE_ALIGN_FLOOR(((val) + ((typeof(val)) (align) - 1)), align)
216
217 /**
218  * Macro to align a pointer to a given power-of-two. The resultant
219  * pointer will be a pointer of the same type as the first parameter, and
220  * point to an address no lower than the first parameter. Second parameter
221  * must be a power-of-two value.
222  * This function is the same as RTE_PTR_ALIGN_CEIL
223  */
224 #define RTE_PTR_ALIGN(ptr, align) RTE_PTR_ALIGN_CEIL(ptr, align)
225
226 /**
227  * Macro to align a value to a given power-of-two. The resultant
228  * value will be of the same type as the first parameter, and
229  * will be no lower than the first parameter. Second parameter
230  * must be a power-of-two value.
231  * This function is the same as RTE_ALIGN_CEIL
232  */
233 #define RTE_ALIGN(val, align) RTE_ALIGN_CEIL(val, align)
234
235 /**
236  * Macro to align a value to the multiple of given value. The resultant
237  * value will be of the same type as the first parameter and will be no lower
238  * than the first parameter.
239  */
240 #define RTE_ALIGN_MUL_CEIL(v, mul) \
241         (((v + (typeof(v))(mul) - 1) / ((typeof(v))(mul))) * (typeof(v))(mul))
242
243 /**
244  * Macro to align a value to the multiple of given value. The resultant
245  * value will be of the same type as the first parameter and will be no higher
246  * than the first parameter.
247  */
248 #define RTE_ALIGN_MUL_FLOOR(v, mul) \
249         ((v / ((typeof(v))(mul))) * (typeof(v))(mul))
250
251 /**
252  * Macro to align value to the nearest multiple of the given value.
253  * The resultant value might be greater than or less than the first parameter
254  * whichever difference is the lowest.
255  */
256 #define RTE_ALIGN_MUL_NEAR(v, mul)                              \
257         ({                                                      \
258                 typeof(v) ceil = RTE_ALIGN_MUL_CEIL(v, mul);    \
259                 typeof(v) floor = RTE_ALIGN_MUL_FLOOR(v, mul);  \
260                 (ceil - v) > (v - floor) ? floor : ceil;        \
261         })
262
263 /**
264  * Checks if a pointer is aligned to a given power-of-two value
265  *
266  * @param ptr
267  *   The pointer whose alignment is to be checked
268  * @param align
269  *   The power-of-two value to which the ptr should be aligned
270  *
271  * @return
272  *   True(1) where the pointer is correctly aligned, false(0) otherwise
273  */
274 static inline int
275 rte_is_aligned(void *ptr, unsigned align)
276 {
277         return RTE_PTR_ALIGN(ptr, align) == ptr;
278 }
279
280 /*********** Macros for compile type checks ********/
281
282 /**
283  * Triggers an error at compilation time if the condition is true.
284  */
285 #define RTE_BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
286
287 /**
288  * Combines 32b inputs most significant set bits into the least
289  * significant bits to construct a value with the same MSBs as x
290  * but all 1's under it.
291  *
292  * @param x
293  *    The integer whose MSBs need to be combined with its LSBs
294  * @return
295  *    The combined value.
296  */
297 static inline uint32_t
298 rte_combine32ms1b(register uint32_t x)
299 {
300         x |= x >> 1;
301         x |= x >> 2;
302         x |= x >> 4;
303         x |= x >> 8;
304         x |= x >> 16;
305
306         return x;
307 }
308
309 /**
310  * Combines 64b inputs most significant set bits into the least
311  * significant bits to construct a value with the same MSBs as x
312  * but all 1's under it.
313  *
314  * @param v
315  *    The integer whose MSBs need to be combined with its LSBs
316  * @return
317  *    The combined value.
318  */
319 static inline uint64_t
320 rte_combine64ms1b(register uint64_t v)
321 {
322         v |= v >> 1;
323         v |= v >> 2;
324         v |= v >> 4;
325         v |= v >> 8;
326         v |= v >> 16;
327         v |= v >> 32;
328
329         return v;
330 }
331
332 /*********** Macros to work with powers of 2 ********/
333
334 /**
335  * Macro to return 1 if n is a power of 2, 0 otherwise
336  */
337 #define RTE_IS_POWER_OF_2(n) ((n) && !(((n) - 1) & (n)))
338
339 /**
340  * Returns true if n is a power of 2
341  * @param n
342  *     Number to check
343  * @return 1 if true, 0 otherwise
344  */
345 static inline int
346 rte_is_power_of_2(uint32_t n)
347 {
348         return n && !(n & (n - 1));
349 }
350
351 /**
352  * Aligns input parameter to the next power of 2
353  *
354  * @param x
355  *   The integer value to algin
356  *
357  * @return
358  *   Input parameter aligned to the next power of 2
359  */
360 static inline uint32_t
361 rte_align32pow2(uint32_t x)
362 {
363         x--;
364         x = rte_combine32ms1b(x);
365
366         return x + 1;
367 }
368
369 /**
370  * Aligns input parameter to the previous power of 2
371  *
372  * @param x
373  *   The integer value to algin
374  *
375  * @return
376  *   Input parameter aligned to the previous power of 2
377  */
378 static inline uint32_t
379 rte_align32prevpow2(uint32_t x)
380 {
381         x = rte_combine32ms1b(x);
382
383         return x - (x >> 1);
384 }
385
386 /**
387  * Aligns 64b input parameter to the next power of 2
388  *
389  * @param v
390  *   The 64b value to align
391  *
392  * @return
393  *   Input parameter aligned to the next power of 2
394  */
395 static inline uint64_t
396 rte_align64pow2(uint64_t v)
397 {
398         v--;
399         v = rte_combine64ms1b(v);
400
401         return v + 1;
402 }
403
404 /**
405  * Aligns 64b input parameter to the previous power of 2
406  *
407  * @param v
408  *   The 64b value to align
409  *
410  * @return
411  *   Input parameter aligned to the previous power of 2
412  */
413 static inline uint64_t
414 rte_align64prevpow2(uint64_t v)
415 {
416         v = rte_combine64ms1b(v);
417
418         return v - (v >> 1);
419 }
420
421 /*********** Macros for calculating min and max **********/
422
423 /**
424  * Macro to return the minimum of two numbers
425  */
426 #define RTE_MIN(a, b) \
427         __extension__ ({ \
428                 typeof (a) _a = (a); \
429                 typeof (b) _b = (b); \
430                 _a < _b ? _a : _b; \
431         })
432
433 /**
434  * Macro to return the maximum of two numbers
435  */
436 #define RTE_MAX(a, b) \
437         __extension__ ({ \
438                 typeof (a) _a = (a); \
439                 typeof (b) _b = (b); \
440                 _a > _b ? _a : _b; \
441         })
442
443 /*********** Other general functions / macros ********/
444
445 /**
446  * Searches the input parameter for the least significant set bit
447  * (starting from zero).
448  * If a least significant 1 bit is found, its bit index is returned.
449  * If the content of the input parameter is zero, then the content of the return
450  * value is undefined.
451  * @param v
452  *     input parameter, should not be zero.
453  * @return
454  *     least significant set bit in the input parameter.
455  */
456 static inline uint32_t
457 rte_bsf32(uint32_t v)
458 {
459         return (uint32_t)__builtin_ctz(v);
460 }
461
462 /**
463  * Searches the input parameter for the least significant set bit
464  * (starting from zero). Safe version (checks for input parameter being zero).
465  *
466  * @warning ``pos`` must be a valid pointer. It is not checked!
467  *
468  * @param v
469  *     The input parameter.
470  * @param pos
471  *     If ``v`` was not 0, this value will contain position of least significant
472  *     bit within the input parameter.
473  * @return
474  *     Returns 0 if ``v`` was 0, otherwise returns 1.
475  */
476 static inline int
477 rte_bsf32_safe(uint64_t v, uint32_t *pos)
478 {
479         if (v == 0)
480                 return 0;
481
482         *pos = rte_bsf32(v);
483         return 1;
484 }
485
486 /**
487  * Return the rounded-up log2 of a integer.
488  *
489  * @param v
490  *     The input parameter.
491  * @return
492  *     The rounded-up log2 of the input, or 0 if the input is 0.
493  */
494 static inline uint32_t
495 rte_log2_u32(uint32_t v)
496 {
497         if (v == 0)
498                 return 0;
499         v = rte_align32pow2(v);
500         return rte_bsf32(v);
501 }
502
503
504 /**
505  * Return the last (most-significant) bit set.
506  *
507  * @note The last (most significant) bit is at position 32.
508  * @note rte_fls_u32(0) = 0, rte_fls_u32(1) = 1, rte_fls_u32(0x80000000) = 32
509  *
510  * @param x
511  *     The input parameter.
512  * @return
513  *     The last (most-significant) bit set, or 0 if the input is 0.
514  */
515 static inline int
516 rte_fls_u32(uint32_t x)
517 {
518         return (x == 0) ? 0 : 32 - __builtin_clz(x);
519 }
520
521 /**
522  * Searches the input parameter for the least significant set bit
523  * (starting from zero).
524  * If a least significant 1 bit is found, its bit index is returned.
525  * If the content of the input parameter is zero, then the content of the return
526  * value is undefined.
527  * @param v
528  *     input parameter, should not be zero.
529  * @return
530  *     least significant set bit in the input parameter.
531  */
532 static inline int
533 rte_bsf64(uint64_t v)
534 {
535         return (uint32_t)__builtin_ctzll(v);
536 }
537
538 /**
539  * Searches the input parameter for the least significant set bit
540  * (starting from zero). Safe version (checks for input parameter being zero).
541  *
542  * @warning ``pos`` must be a valid pointer. It is not checked!
543  *
544  * @param v
545  *     The input parameter.
546  * @param pos
547  *     If ``v`` was not 0, this value will contain position of least significant
548  *     bit within the input parameter.
549  * @return
550  *     Returns 0 if ``v`` was 0, otherwise returns 1.
551  */
552 static inline int
553 rte_bsf64_safe(uint64_t v, uint32_t *pos)
554 {
555         if (v == 0)
556                 return 0;
557
558         *pos = rte_bsf64(v);
559         return 1;
560 }
561
562 /**
563  * Return the last (most-significant) bit set.
564  *
565  * @note The last (most significant) bit is at position 64.
566  * @note rte_fls_u64(0) = 0, rte_fls_u64(1) = 1,
567  *       rte_fls_u64(0x8000000000000000) = 64
568  *
569  * @param x
570  *     The input parameter.
571  * @return
572  *     The last (most-significant) bit set, or 0 if the input is 0.
573  */
574 static inline int
575 rte_fls_u64(uint64_t x)
576 {
577         return (x == 0) ? 0 : 64 - __builtin_clzll(x);
578 }
579
580 /**
581  * Return the rounded-up log2 of a 64-bit integer.
582  *
583  * @param v
584  *     The input parameter.
585  * @return
586  *     The rounded-up log2 of the input, or 0 if the input is 0.
587  */
588 static inline uint32_t
589 rte_log2_u64(uint64_t v)
590 {
591         if (v == 0)
592                 return 0;
593         v = rte_align64pow2(v);
594         /* we checked for v being 0 already, so no undefined behavior */
595         return rte_bsf64(v);
596 }
597
598 #ifndef offsetof
599 /** Return the offset of a field in a structure. */
600 #define offsetof(TYPE, MEMBER)  __builtin_offsetof (TYPE, MEMBER)
601 #endif
602
603 /**
604  * Return pointer to the wrapping struct instance.
605  *
606  * Example:
607  *
608  *  struct wrapper {
609  *      ...
610  *      struct child c;
611  *      ...
612  *  };
613  *
614  *  struct child *x = obtain(...);
615  *  struct wrapper *w = container_of(x, struct wrapper, c);
616  */
617 #ifndef container_of
618 #define container_of(ptr, type, member) __extension__ ({                \
619                         const typeof(((type *)0)->member) *_ptr = (ptr); \
620                         __attribute__((unused)) type *_target_ptr =     \
621                                 (type *)(ptr);                          \
622                         (type *)(((uintptr_t)_ptr) - offsetof(type, member)); \
623                 })
624 #endif
625
626 #define _RTE_STR(x) #x
627 /** Take a macro value and get a string version of it */
628 #define RTE_STR(x) _RTE_STR(x)
629
630 /**
631  * ISO C helpers to modify format strings using variadic macros.
632  * This is a replacement for the ", ## __VA_ARGS__" GNU extension.
633  * An empty %s argument is appended to avoid a dangling comma.
634  */
635 #define RTE_FMT(fmt, ...) fmt "%.0s", __VA_ARGS__ ""
636 #define RTE_FMT_HEAD(fmt, ...) fmt
637 #define RTE_FMT_TAIL(fmt, ...) __VA_ARGS__
638
639 /** Mask value of type "tp" for the first "ln" bit set. */
640 #define RTE_LEN2MASK(ln, tp)    \
641         ((tp)((uint64_t)-1 >> (sizeof(uint64_t) * CHAR_BIT - (ln))))
642
643 /** Number of elements in the array. */
644 #define RTE_DIM(a)      (sizeof (a) / sizeof ((a)[0]))
645
646 /**
647  * Converts a numeric string to the equivalent uint64_t value.
648  * As well as straight number conversion, also recognises the suffixes
649  * k, m and g for kilobytes, megabytes and gigabytes respectively.
650  *
651  * If a negative number is passed in  i.e. a string with the first non-black
652  * character being "-", zero is returned. Zero is also returned in the case of
653  * an error with the strtoull call in the function.
654  *
655  * @param str
656  *     String containing number to convert.
657  * @return
658  *     Number.
659  */
660 static inline uint64_t
661 rte_str_to_size(const char *str)
662 {
663         char *endptr;
664         unsigned long long size;
665
666         while (isspace((int)*str))
667                 str++;
668         if (*str == '-')
669                 return 0;
670
671         errno = 0;
672         size = strtoull(str, &endptr, 0);
673         if (errno)
674                 return 0;
675
676         if (*endptr == ' ')
677                 endptr++; /* allow 1 space gap */
678
679         switch (*endptr){
680         case 'G': case 'g': size *= 1024; /* fall-through */
681         case 'M': case 'm': size *= 1024; /* fall-through */
682         case 'K': case 'k': size *= 1024; /* fall-through */
683         default:
684                 break;
685         }
686         return size;
687 }
688
689 /**
690  * Function to terminate the application immediately, printing an error
691  * message and returning the exit_code back to the shell.
692  *
693  * This function never returns
694  *
695  * @param exit_code
696  *     The exit code to be returned by the application
697  * @param format
698  *     The format string to be used for printing the message. This can include
699  *     printf format characters which will be expanded using any further parameters
700  *     to the function.
701  */
702 void
703 rte_exit(int exit_code, const char *format, ...)
704         __attribute__((noreturn))
705         __attribute__((format(printf, 2, 3)));
706
707 #ifdef __cplusplus
708 }
709 #endif
710
711 #endif