vppinfra: add clear_lowest_set_bit() function, use BMI2 if available
[vpp.git] / src / vppinfra / clib.h
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16   Copyright (c) 2001, 2002, 2003 Eliot Dresselhaus
17
18   Permission is hereby granted, free of charge, to any person obtaining
19   a copy of this software and associated documentation files (the
20   "Software"), to deal in the Software without restriction, including
21   without limitation the rights to use, copy, modify, merge, publish,
22   distribute, sublicense, and/or sell copies of the Software, and to
23   permit persons to whom the Software is furnished to do so, subject to
24   the following conditions:
25
26   The above copyright notice and this permission notice shall be
27   included in all copies or substantial portions of the Software.
28
29   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
33   LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
34   OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35   WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 */
37
38 #ifndef included_clib_h
39 #define included_clib_h
40
41 #include <stddef.h>
42 #include <vppinfra/config.h>
43
44 #ifdef  __x86_64__
45 #include <x86intrin.h>
46 #endif
47
48 /* Standalone means to not assume we are running on a Unix box. */
49 #if ! defined (CLIB_STANDALONE) && ! defined (CLIB_LINUX_KERNEL)
50 #define CLIB_UNIX
51 #endif
52
53 #include <vppinfra/types.h>
54 #include <vppinfra/atomics.h>
55
56 /* Global DEBUG flag.  Setting this to 1 or 0 turns off
57    ASSERT (see vppinfra/error.h) & other debugging code. */
58 #ifndef CLIB_DEBUG
59 #define CLIB_DEBUG 0
60 #endif
61
62 #ifndef NULL
63 #define NULL ((void *) 0)
64 #endif
65
66 #define BITS(x)         (8*sizeof(x))
67 #define ARRAY_LEN(x)    (sizeof (x)/sizeof (x[0]))
68
69 #define _STRUCT_FIELD(t,f) (((t *) 0)->f)
70 #define STRUCT_OFFSET_OF(t,f) offsetof(t, f)
71 #define STRUCT_BIT_OFFSET_OF(t,f) (BITS(u8) * STRUCT_OFFSET_OF (t, f))
72 #define STRUCT_SIZE_OF(t,f)   (sizeof (_STRUCT_FIELD (t, f)))
73 #define STRUCT_BITS_OF(t,f)   (BITS (_STRUCT_FIELD (t, f)))
74 #define STRUCT_ARRAY_LEN(t,f) ARRAY_LEN (_STRUCT_FIELD (t, f))
75 #define STRUCT_MARK(mark)     u8 mark[0]
76 #define STRUCT_MARK_PTR(v, f) &(v)->f
77
78 /* Stride in bytes between struct array elements. */
79 #define STRUCT_STRIDE_OF(t,f)                   \
80   (  ((uword) & (((t *) 0)[1].f))               \
81    - ((uword) & (((t *) 0)[0].f)))
82
83 #define STRUCT_OFFSET_OF_VAR(v,f) ((uword) (&(v)->f) - (uword) (v))
84
85 /* Used to pack structure elements. */
86 #define CLIB_PACKED(x)  x __attribute__ ((packed))
87 #define CLIB_UNUSED(x)  x __attribute__ ((unused))
88
89 /* similar to CLIB_CACHE_LINE_ALIGN_MARK() but with arbitrary alignment */
90 #define CLIB_ALIGN_MARK(name, alignment) u8 name[0] __attribute__((aligned(alignment)))
91
92 /* Make a string from the macro's argument */
93 #define CLIB_STRING_MACRO(x) #x
94
95 #define __clib_unused __attribute__ ((unused))
96 #define __clib_weak __attribute__ ((weak))
97 #define __clib_packed __attribute__ ((packed))
98 #define __clib_constructor __attribute__ ((constructor))
99 #define __clib_noinline __attribute__ ((noinline))
100 #define __clib_aligned(x) __attribute__ ((aligned(x)))
101 #define __clib_section(s) __attribute__ ((section(s)))
102 #define __clib_warn_unused_result __attribute__ ((warn_unused_result))
103 #define __clib_export __attribute__ ((visibility("default")))
104
105 #define never_inline __attribute__ ((__noinline__))
106
107 #if CLIB_DEBUG > 0
108 #define always_inline static inline
109 #define static_always_inline static inline
110 #else
111 #define always_inline static inline __attribute__ ((__always_inline__))
112 #define static_always_inline static inline __attribute__ ((__always_inline__))
113 #endif
114
115
116 /* Reserved (unused) structure element with address offset between
117    from and to. */
118 #define CLIB_PAD_FROM_TO(from,to) u8 pad_##from[(to) - (from)]
119
120 /* Hints to compiler about hot/cold code. */
121 #define PREDICT_FALSE(x) __builtin_expect((x),0)
122 #define PREDICT_TRUE(x) __builtin_expect((x),1)
123
124 /*
125  * Compiler barrier
126  *   prevent compiler to reorder memory access accross this boundary
127  *   prevent compiler to cache values in register (force reload)
128  * Not to be confused with CPU memory barrier below
129  */
130 #define CLIB_COMPILER_BARRIER() asm volatile ("":::"memory")
131
132 /* Full memory barrier (read and write). */
133 #define CLIB_MEMORY_BARRIER() __sync_synchronize ()
134
135 #if __x86_64__
136 #define CLIB_MEMORY_STORE_BARRIER() __builtin_ia32_sfence ()
137 #else
138 #define CLIB_MEMORY_STORE_BARRIER() __sync_synchronize ()
139 #endif
140
141 /* Arranges for function to be called before main. */
142 #define INIT_FUNCTION(decl)                     \
143   decl __attribute ((constructor));             \
144   decl
145
146 /* Arranges for function to be called before exit. */
147 #define EXIT_FUNCTION(decl)                     \
148   decl __attribute ((destructor));              \
149   decl
150
151 /* Use __builtin_clz if available. */
152 #if uword_bits == 64
153 #define count_leading_zeros(x) __builtin_clzll (x)
154 #define count_trailing_zeros(x) __builtin_ctzll (x)
155 #else
156 #define count_leading_zeros(x) __builtin_clzl (x)
157 #define count_trailing_zeros(x) __builtin_ctzl (x)
158 #endif
159
160 #if defined (count_leading_zeros)
161 always_inline uword
162 clear_lowest_set_bit (uword x)
163 {
164 #ifdef __BMI2__
165   return _blsr_u64 (x);
166 #else
167   return x ^ (1ULL << count_trailing_zeros (x));
168 #endif
169 }
170
171 always_inline uword
172 min_log2 (uword x)
173 {
174   uword n;
175   n = count_leading_zeros (x);
176   return BITS (uword) - n - 1;
177 }
178 #else
179 always_inline uword
180 min_log2 (uword x)
181 {
182   uword a = x, b = BITS (uword) / 2, c = 0, r = 0;
183
184   /* Reduce x to 4 bit result. */
185 #define _                                       \
186 {                                               \
187   c = a >> b;                                   \
188   if (c) a = c;                                 \
189   if (c) r += b;                                \
190   b /= 2;                                       \
191 }
192
193   if (BITS (uword) > 32)
194     _;
195   _;
196   _;
197   _;
198 #undef _
199
200   /* Do table lookup on 4 bit partial. */
201   if (BITS (uword) > 32)
202     {
203       const u64 table = 0x3333333322221104LL;
204       uword t = (table >> (4 * a)) & 0xf;
205       r = t < 4 ? r + t : ~0;
206     }
207   else
208     {
209       const u32 table = 0x22221104;
210       uword t = (a & 8) ? 3 : ((table >> (4 * a)) & 0xf);
211       r = t < 4 ? r + t : ~0;
212     }
213
214   return r;
215 }
216 #endif
217
218 always_inline uword
219 max_log2 (uword x)
220 {
221   uword l = min_log2 (x);
222   if (x > ((uword) 1 << l))
223     l++;
224   return l;
225 }
226
227 always_inline u64
228 min_log2_u64 (u64 x)
229 {
230   if (BITS (uword) == 64)
231     return min_log2 (x);
232   else
233     {
234       uword l, y;
235       y = x;
236       l = 0;
237       if (y == 0)
238         {
239           l += 32;
240           x >>= 32;
241         }
242       l += min_log2 (x);
243       return l;
244     }
245 }
246
247 always_inline uword
248 pow2_mask (uword x)
249 {
250   return ((uword) 1 << x) - (uword) 1;
251 }
252
253 always_inline uword
254 max_pow2 (uword x)
255 {
256   word y = (word) 1 << min_log2 (x);
257   if (x > y)
258     y *= 2;
259   return y;
260 }
261
262 always_inline uword
263 is_pow2 (uword x)
264 {
265   return 0 == (x & (x - 1));
266 }
267
268 always_inline uword
269 round_down_pow2 (uword x, uword pow2)
270 {
271   return (x) & ~(pow2 - 1);
272 }
273
274 always_inline uword
275 round_pow2 (uword x, uword pow2)
276 {
277   return (x + pow2 - 1) & ~(pow2 - 1);
278 }
279
280 always_inline u64
281 round_pow2_u64 (u64 x, u64 pow2)
282 {
283   return (x + pow2 - 1) & ~(pow2 - 1);
284 }
285
286 always_inline uword
287 first_set (uword x)
288 {
289   return x & -x;
290 }
291
292 always_inline uword
293 log2_first_set (uword x)
294 {
295   uword result;
296 #ifdef count_trailing_zeros
297   result = count_trailing_zeros (x);
298 #else
299   result = min_log2 (first_set (x));
300 #endif
301   return result;
302 }
303
304 always_inline f64
305 flt_round_down (f64 x)
306 {
307   return (int) x;
308 }
309
310 always_inline word
311 flt_round_nearest (f64 x)
312 {
313   return (word) (x + .5);
314 }
315
316 always_inline f64
317 flt_round_to_multiple (f64 x, f64 f)
318 {
319   return f * flt_round_nearest (x / f);
320 }
321
322 always_inline uword
323 extract_bits (uword x, int start, int count)
324 {
325 #ifdef __BMI__
326   return _bextr_u64 (x, start, count);
327 #endif
328   return (x >> start) & pow2_mask (count);
329 }
330
331 #define clib_max(x,y)                           \
332 ({                                              \
333   __typeof__ (x) _x = (x);                      \
334   __typeof__ (y) _y = (y);                      \
335   _x > _y ? _x : _y;                            \
336 })
337
338 #define clib_min(x,y)                           \
339 ({                                              \
340   __typeof__ (x) _x = (x);                      \
341   __typeof__ (y) _y = (y);                      \
342   _x < _y ? _x : _y;                            \
343 })
344
345 #define clib_clamp(x,lo,hi)                     \
346 ({                                              \
347   __typeof__ (x) _x = (x);                      \
348   __typeof__ (lo) _lo = (lo);                   \
349   __typeof__ (hi) _hi = (hi);                   \
350   _x < _lo ? _lo : (_x > _hi ? _hi : _x);       \
351 })
352
353 #define clib_abs(x)                             \
354 ({                                              \
355   __typeof__ (x) _x = (x);                      \
356   _x < 0 ? -_x : _x;                            \
357 })
358
359 /* Standard standalone-only function declarations. */
360 #ifndef CLIB_UNIX
361 void clib_standalone_init (void *memory, uword memory_bytes);
362
363 void qsort (void *base, uword n, uword size,
364             int (*)(const void *, const void *));
365 #endif
366
367 /* Stack backtrace. */
368 uword
369 clib_backtrace (uword * callers, uword max_callers, uword n_frames_to_skip);
370
371 #endif /* included_clib_h */
372
373 /*
374  * fd.io coding-style-patch-verification: ON
375  *
376  * Local Variables:
377  * eval: (c-set-style "gnu")
378  * End:
379  */