util: Add be32_prefix_mask().
[cascardo/ovs.git] / lib / util.h
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef UTIL_H
18 #define UTIL_H 1
19
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <stdarg.h>
23 #include <stdbool.h>
24 #include <stddef.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include "byte-order.h"
30 #include "compiler.h"
31 #include "openvswitch/types.h"
32
33 #ifndef va_copy
34 #ifdef __va_copy
35 #define va_copy __va_copy
36 #else
37 #define va_copy(dst, src) ((dst) = (src))
38 #endif
39 #endif
40
41 #ifdef __CHECKER__
42 #define BUILD_ASSERT(EXPR) ((void) 0)
43 #define BUILD_ASSERT_DECL(EXPR) extern int (*build_assert(void))[1]
44 #elif !defined(__cplusplus)
45 /* Build-time assertion building block. */
46 #define BUILD_ASSERT__(EXPR) \
47         sizeof(struct { unsigned int build_assert_failed : (EXPR) ? 1 : -1; })
48
49 /* Build-time assertion for use in a statement context. */
50 #define BUILD_ASSERT(EXPR) (void) BUILD_ASSERT__(EXPR)
51
52 /* Build-time assertion for use in a declaration context. */
53 #define BUILD_ASSERT_DECL(EXPR) \
54         extern int (*build_assert(void))[BUILD_ASSERT__(EXPR)]
55 #else /* __cplusplus */
56 #include <boost/static_assert.hpp>
57 #define BUILD_ASSERT BOOST_STATIC_ASSERT
58 #define BUILD_ASSERT_DECL BOOST_STATIC_ASSERT
59 #endif /* __cplusplus */
60
61 #ifdef __GNUC__
62 #define BUILD_ASSERT_GCCONLY(EXPR) BUILD_ASSERT(EXPR)
63 #define BUILD_ASSERT_DECL_GCCONLY(EXPR) BUILD_ASSERT_DECL(EXPR)
64 #else
65 #define BUILD_ASSERT_GCCONLY(EXPR) ((void) 0)
66 #define BUILD_ASSERT_DECL_GCCONLY(EXPR) ((void) 0)
67 #endif
68
69 /* Like the standard assert macro, except:
70  *
71  *   - Writes the failure message to the log.
72  *
73  *   - Not affected by NDEBUG. */
74 #define ovs_assert(CONDITION)                                           \
75     if (!OVS_LIKELY(CONDITION)) {                                       \
76         ovs_assert_failure(SOURCE_LOCATOR, __func__, #CONDITION);       \
77     }
78 void ovs_assert_failure(const char *, const char *, const char *) NO_RETURN;
79
80 /* Casts 'pointer' to 'type' and issues a compiler warning if the cast changes
81  * anything other than an outermost "const" or "volatile" qualifier.
82  *
83  * The cast to int is present only to suppress an "expression using sizeof
84  * bool" warning from "sparse" (see
85  * http://permalink.gmane.org/gmane.comp.parsers.sparse/2967). */
86 #define CONST_CAST(TYPE, POINTER)                               \
87     ((void) sizeof ((int) ((POINTER) == (TYPE) (POINTER))),     \
88      (TYPE) (POINTER))
89
90 extern char *program_name;
91
92 #define __ARRAY_SIZE_NOCHECK(ARRAY) (sizeof(ARRAY) / sizeof((ARRAY)[0]))
93 #ifdef __GNUC__
94 /* return 0 for array types, 1 otherwise */
95 #define __ARRAY_CHECK(ARRAY)                                    \
96     !__builtin_types_compatible_p(typeof(ARRAY), typeof(&ARRAY[0]))
97
98 /* compile-time fail if not array */
99 #define __ARRAY_FAIL(ARRAY) (sizeof(char[-2*!__ARRAY_CHECK(ARRAY)]))
100 #define __ARRAY_SIZE(ARRAY)                                     \
101     __builtin_choose_expr(__ARRAY_CHECK(ARRAY),                 \
102         __ARRAY_SIZE_NOCHECK(ARRAY), __ARRAY_FAIL(ARRAY))
103 #else
104 #define __ARRAY_SIZE(ARRAY) __ARRAY_SIZE_NOCHECK(ARRAY)
105 #endif
106
107 /* Returns the number of elements in ARRAY. */
108 #define ARRAY_SIZE(ARRAY) __ARRAY_SIZE(ARRAY)
109
110 /* Returns X / Y, rounding up.  X must be nonnegative to round correctly. */
111 #define DIV_ROUND_UP(X, Y) (((X) + ((Y) - 1)) / (Y))
112
113 /* Returns X rounded up to the nearest multiple of Y. */
114 #define ROUND_UP(X, Y) (DIV_ROUND_UP(X, Y) * (Y))
115
116 /* Returns the least number that, when added to X, yields a multiple of Y. */
117 #define PAD_SIZE(X, Y) (ROUND_UP(X, Y) - (X))
118
119 /* Returns X rounded down to the nearest multiple of Y. */
120 #define ROUND_DOWN(X, Y) ((X) / (Y) * (Y))
121
122 /* Returns true if X is a power of 2, otherwise false. */
123 #define IS_POW2(X) ((X) && !((X) & ((X) - 1)))
124
125 static inline bool
126 is_pow2(uintmax_t x)
127 {
128     return IS_POW2(x);
129 }
130
131 /* Returns X rounded up to a power of 2.  X must be a constant expression. */
132 #define ROUND_UP_POW2(X) RUP2__(X)
133 #define RUP2__(X) (RUP2_1(X) + 1)
134 #define RUP2_1(X) (RUP2_2(X) | (RUP2_2(X) >> 16))
135 #define RUP2_2(X) (RUP2_3(X) | (RUP2_3(X) >> 8))
136 #define RUP2_3(X) (RUP2_4(X) | (RUP2_4(X) >> 4))
137 #define RUP2_4(X) (RUP2_5(X) | (RUP2_5(X) >> 2))
138 #define RUP2_5(X) (RUP2_6(X) | (RUP2_6(X) >> 1))
139 #define RUP2_6(X) ((X) - 1)
140
141 /* Returns X rounded down to a power of 2.  X must be a constant expression. */
142 #define ROUND_DOWN_POW2(X) RDP2__(X)
143 #define RDP2__(X) (RDP2_1(X) - (RDP2_1(X) >> 1))
144 #define RDP2_1(X) (RDP2_2(X) | (RDP2_2(X) >> 16))
145 #define RDP2_2(X) (RDP2_3(X) | (RDP2_3(X) >> 8))
146 #define RDP2_3(X) (RDP2_4(X) | (RDP2_4(X) >> 4))
147 #define RDP2_4(X) (RDP2_5(X) | (RDP2_5(X) >> 2))
148 #define RDP2_5(X) (      (X) | (      (X) >> 1))
149
150 /* This system's cache line size, in bytes.
151  * Being wrong hurts performance but not correctness. */
152 #define CACHE_LINE_SIZE 64
153 BUILD_ASSERT_DECL(IS_POW2(CACHE_LINE_SIZE));
154
155 static inline void
156 ovs_prefetch_range(const void *start, size_t size)
157 {
158     const char *addr = (const char *)start;
159     size_t ofs;
160
161     for (ofs = 0; ofs < size; ofs += CACHE_LINE_SIZE) {
162         OVS_PREFETCH(addr + ofs);
163     }
164 }
165
166 #ifndef MIN
167 #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
168 #endif
169
170 #ifndef MAX
171 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
172 #endif
173
174 #define OVS_NOT_REACHED() abort()
175
176 /* Expands to a string that looks like "<file>:<line>", e.g. "tmp.c:10".
177  *
178  * See http://c-faq.com/ansi/stringize.html for an explanation of STRINGIZE and
179  * STRINGIZE2. */
180 #define SOURCE_LOCATOR __FILE__ ":" STRINGIZE(__LINE__)
181 #define STRINGIZE(ARG) STRINGIZE2(ARG)
182 #define STRINGIZE2(ARG) #ARG
183
184 /* Given a pointer-typed lvalue OBJECT, expands to a pointer type that may be
185  * assigned to OBJECT. */
186 #ifdef __GNUC__
187 #define OVS_TYPEOF(OBJECT) typeof(OBJECT)
188 #else
189 #define OVS_TYPEOF(OBJECT) void *
190 #endif
191
192 /* Given OBJECT of type pointer-to-structure, expands to the offset of MEMBER
193  * within an instance of the structure.
194  *
195  * The GCC-specific version avoids the technicality of undefined behavior if
196  * OBJECT is null, invalid, or not yet initialized.  This makes some static
197  * checkers (like Coverity) happier.  But the non-GCC version does not actually
198  * dereference any pointer, so it would be surprising for it to cause any
199  * problems in practice.
200  */
201 #ifdef __GNUC__
202 #define OBJECT_OFFSETOF(OBJECT, MEMBER) offsetof(typeof(*(OBJECT)), MEMBER)
203 #else
204 #define OBJECT_OFFSETOF(OBJECT, MEMBER) \
205     ((char *) &(OBJECT)->MEMBER - (char *) (OBJECT))
206 #endif
207
208 /* Given POINTER, the address of the given MEMBER in a STRUCT object, returns
209    the STRUCT object. */
210 #define CONTAINER_OF(POINTER, STRUCT, MEMBER)                           \
211         ((STRUCT *) (void *) ((char *) (POINTER) - offsetof (STRUCT, MEMBER)))
212
213 /* Given POINTER, the address of the given MEMBER within an object of the type
214  * that that OBJECT points to, returns OBJECT as an assignment-compatible
215  * pointer type (either the correct pointer type or "void *").  OBJECT must be
216  * an lvalue.
217  *
218  * This is the same as CONTAINER_OF except that it infers the structure type
219  * from the type of '*OBJECT'. */
220 #define OBJECT_CONTAINING(POINTER, OBJECT, MEMBER)                      \
221     ((OVS_TYPEOF(OBJECT)) (void *)                                      \
222      ((char *) (POINTER) - OBJECT_OFFSETOF(OBJECT, MEMBER)))
223
224 /* Given POINTER, the address of the given MEMBER within an object of the type
225  * that that OBJECT points to, assigns the address of the outer object to
226  * OBJECT, which must be an lvalue.
227  *
228  * Evaluates to (void) 0 as the result is not to be used. */
229 #define ASSIGN_CONTAINER(OBJECT, POINTER, MEMBER) \
230     ((OBJECT) = OBJECT_CONTAINING(POINTER, OBJECT, MEMBER), (void) 0)
231
232 /* Given ATTR, and TYPE, cast the ATTR to TYPE by first casting ATTR to
233  * (void *). This is to suppress the alignment warning issued by clang. */
234 #define ALIGNED_CAST(TYPE, ATTR) ((TYPE) (void *) (ATTR))
235
236 /* Use "%"PRIuSIZE to format size_t with printf(). */
237 #ifdef _WIN32
238 #define PRIdSIZE "Id"
239 #define PRIiSIZE "Ii"
240 #define PRIoSIZE "Io"
241 #define PRIuSIZE "Iu"
242 #define PRIxSIZE "Ix"
243 #define PRIXSIZE "IX"
244 #else
245 #define PRIdSIZE "zd"
246 #define PRIiSIZE "zi"
247 #define PRIoSIZE "zo"
248 #define PRIuSIZE "zu"
249 #define PRIxSIZE "zx"
250 #define PRIXSIZE "zX"
251 #endif
252
253 #ifdef  __cplusplus
254 extern "C" {
255 #endif
256
257 void set_program_name__(const char *name, const char *version,
258                         const char *date, const char *time);
259 #define set_program_name(name) \
260         set_program_name__(name, VERSION, __DATE__, __TIME__)
261
262 const char *get_subprogram_name(void);
263 void set_subprogram_name(const char *format, ...) PRINTF_FORMAT(1, 2);
264
265 const char *get_program_version(void);
266 void ovs_print_version(uint8_t min_ofp, uint8_t max_ofp);
267
268 void out_of_memory(void) NO_RETURN;
269 void *xmalloc(size_t) MALLOC_LIKE;
270 void *xcalloc(size_t, size_t) MALLOC_LIKE;
271 void *xzalloc(size_t) MALLOC_LIKE;
272 void *xrealloc(void *, size_t);
273 void *xmemdup(const void *, size_t) MALLOC_LIKE;
274 char *xmemdup0(const char *, size_t) MALLOC_LIKE;
275 char *xstrdup(const char *) MALLOC_LIKE;
276 char *xasprintf(const char *format, ...) PRINTF_FORMAT(1, 2) MALLOC_LIKE;
277 char *xvasprintf(const char *format, va_list) PRINTF_FORMAT(1, 0) MALLOC_LIKE;
278 void *x2nrealloc(void *p, size_t *n, size_t s);
279
280 void *xmalloc_cacheline(size_t) MALLOC_LIKE;
281 void *xzalloc_cacheline(size_t) MALLOC_LIKE;
282 void free_cacheline(void *);
283
284 void ovs_strlcpy(char *dst, const char *src, size_t size);
285 void ovs_strzcpy(char *dst, const char *src, size_t size);
286
287 void ovs_abort(int err_no, const char *format, ...)
288     PRINTF_FORMAT(2, 3) NO_RETURN;
289 void ovs_abort_valist(int err_no, const char *format, va_list)
290     PRINTF_FORMAT(2, 0) NO_RETURN;
291 void ovs_fatal(int err_no, const char *format, ...)
292     PRINTF_FORMAT(2, 3) NO_RETURN;
293 void ovs_fatal_valist(int err_no, const char *format, va_list)
294     PRINTF_FORMAT(2, 0) NO_RETURN;
295 void ovs_error(int err_no, const char *format, ...) PRINTF_FORMAT(2, 3);
296 void ovs_error_valist(int err_no, const char *format, va_list)
297     PRINTF_FORMAT(2, 0);
298 const char *ovs_retval_to_string(int);
299 const char *ovs_strerror(int);
300 void ovs_hex_dump(FILE *, const void *, size_t, uintptr_t offset, bool ascii);
301
302 bool str_to_int(const char *, int base, int *);
303 bool str_to_long(const char *, int base, long *);
304 bool str_to_llong(const char *, int base, long long *);
305 bool str_to_uint(const char *, int base, unsigned int *);
306
307 bool ovs_scan(const char *s, const char *format, ...) SCANF_FORMAT(2, 3);
308
309 bool str_to_double(const char *, double *);
310
311 int hexit_value(int c);
312 unsigned int hexits_value(const char *s, size_t n, bool *ok);
313
314 const char *english_list_delimiter(size_t index, size_t total);
315
316 char *get_cwd(void);
317 char *dir_name(const char *file_name);
318 char *base_name(const char *file_name);
319 char *abs_file_name(const char *dir, const char *file_name);
320
321 char *follow_symlinks(const char *filename);
322
323 void ignore(bool x OVS_UNUSED);
324 \f
325 /* Bitwise tests. */
326
327 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
328 #if __GNUC__ >= 4
329 static inline int
330 raw_ctz(uint64_t n)
331 {
332     /* With GCC 4.7 on 32-bit x86, if a 32-bit integer is passed as 'n', using
333      * a plain __builtin_ctzll() here always generates an out-of-line function
334      * call.  The test below helps it to emit a single 'bsf' instruction. */
335     return (__builtin_constant_p(n <= UINT32_MAX) && n <= UINT32_MAX
336             ? __builtin_ctz(n)
337             : __builtin_ctzll(n));
338 }
339
340 static inline int
341 raw_clz64(uint64_t n)
342 {
343     return __builtin_clzll(n);
344 }
345 #else
346 /* Defined in util.c. */
347 int raw_ctz(uint64_t n);
348 int raw_clz64(uint64_t n);
349 #endif
350
351 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
352 static inline int
353 ctz32(uint32_t n)
354 {
355     return n ? raw_ctz(n) : 32;
356 }
357
358 /* Returns the number of trailing 0-bits in 'n', or 64 if 'n' is 0. */
359 static inline int
360 ctz64(uint64_t n)
361 {
362     return n ? raw_ctz(n) : 64;
363 }
364
365 /* Returns the number of leading 0-bits in 'n', or 32 if 'n' is 0. */
366 static inline int
367 clz32(uint32_t n)
368 {
369     return n ? raw_clz64(n) - 32 : 32;
370 }
371
372 /* Returns the number of leading 0-bits in 'n', or 64 if 'n' is 0. */
373 static inline int
374 clz64(uint64_t n)
375 {
376     return n ? raw_clz64(n) : 64;
377 }
378
379 /* Given a word 'n', calculates floor(log_2('n')).  This is equivalent
380  * to finding the bit position of the most significant one bit in 'n'.  It is
381  * an error to call this function with 'n' == 0. */
382 static inline int
383 log_2_floor(uint64_t n)
384 {
385     return 63 - raw_clz64(n);
386 }
387
388 /* Given a word 'n', calculates ceil(log_2('n')).  It is an error to
389  * call this function with 'n' == 0. */
390 static inline int
391 log_2_ceil(uint64_t n)
392 {
393     return log_2_floor(n) + !is_pow2(n);
394 }
395
396 /* unsigned int count_1bits(uint64_t x):
397  *
398  * Returns the number of 1-bits in 'x', between 0 and 64 inclusive. */
399 #if UINTPTR_MAX == UINT64_MAX
400 static inline unsigned int
401 count_1bits(uint64_t x)
402 {
403 #if __GNUC__ >= 4 && __POPCNT__
404     return __builtin_popcountll(x);
405 #else
406     /* This portable implementation is the fastest one we know of for 64
407      * bits, and about 3x faster than GCC 4.7 __builtin_popcountll(). */
408     const uint64_t h55 = UINT64_C(0x5555555555555555);
409     const uint64_t h33 = UINT64_C(0x3333333333333333);
410     const uint64_t h0F = UINT64_C(0x0F0F0F0F0F0F0F0F);
411     const uint64_t h01 = UINT64_C(0x0101010101010101);
412     x -= (x >> 1) & h55;               /* Count of each 2 bits in-place. */
413     x = (x & h33) + ((x >> 2) & h33);  /* Count of each 4 bits in-place. */
414     x = (x + (x >> 4)) & h0F;          /* Count of each 8 bits in-place. */
415     return (x * h01) >> 56;            /* Sum of all bytes. */
416 #endif
417 }
418 #else /* Not 64-bit. */
419 #if __GNUC__ >= 4 && __POPCNT__
420 static inline unsigned int
421 count_1bits_32__(uint32_t x)
422 {
423     return __builtin_popcount(x);
424 }
425 #else
426 #define NEED_COUNT_1BITS_8 1
427 extern const uint8_t count_1bits_8[256];
428 static inline unsigned int
429 count_1bits_32__(uint32_t x)
430 {
431     /* This portable implementation is the fastest one we know of for 32 bits,
432      * and faster than GCC __builtin_popcount(). */
433     return (count_1bits_8[x & 0xff] +
434             count_1bits_8[(x >> 8) & 0xff] +
435             count_1bits_8[(x >> 16) & 0xff] +
436             count_1bits_8[x >> 24]);
437 }
438 #endif
439 static inline unsigned int
440 count_1bits(uint64_t x)
441 {
442     return count_1bits_32__(x) + count_1bits_32__(x >> 32);
443 }
444 #endif
445
446 /* Returns the rightmost 1-bit in 'x' (e.g. 01011000 => 00001000), or 0 if 'x'
447  * is 0. */
448 static inline uintmax_t
449 rightmost_1bit(uintmax_t x)
450 {
451     return x & -x;
452 }
453
454 /* Returns 'x' with its rightmost 1-bit changed to a zero (e.g. 01011000 =>
455  * 01010000), or 0 if 'x' is 0. */
456 static inline uintmax_t
457 zero_rightmost_1bit(uintmax_t x)
458 {
459     return x & (x - 1);
460 }
461
462 /* Returns the index of the rightmost 1-bit in 'x' (e.g. 01011000 => 3), or 32
463  * if 'x' is 0.
464  *
465  * Unlike the other functions for rightmost 1-bits, this function only works
466  * with 32-bit integers. */
467 static inline uint32_t
468 rightmost_1bit_idx(uint32_t x)
469 {
470     return ctz32(x);
471 }
472
473 /* Returns the index of the leftmost 1-bit in 'x' (e.g. 01011000 => 6), or 32
474  * if 'x' is 0.
475  *
476  * This function only works with 32-bit integers. */
477 static inline uint32_t
478 leftmost_1bit_idx(uint32_t x)
479 {
480     return x ? log_2_floor(x) : 32;
481 }
482
483 /* Return a ovs_be32 prefix in network byte order with 'plen' highest bits set.
484  * Shift with 32 is undefined behavior, but we rather use 64-bit shift than
485  * compare. */
486 static inline ovs_be32 be32_prefix_mask(int plen)
487 {
488     return htonl((uint64_t)UINT32_MAX << (32 - plen));
489 }
490 \f
491 bool is_all_zeros(const uint8_t *, size_t);
492 bool is_all_ones(const uint8_t *, size_t);
493 void bitwise_copy(const void *src, unsigned int src_len, unsigned int src_ofs,
494                   void *dst, unsigned int dst_len, unsigned int dst_ofs,
495                   unsigned int n_bits);
496 void bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
497                   unsigned int n_bits);
498 void bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
499                  unsigned int n_bits);
500 bool bitwise_is_all_zeros(const void *, unsigned int len, unsigned int ofs,
501                           unsigned int n_bits);
502 void bitwise_put(uint64_t value,
503                  void *dst, unsigned int dst_len, unsigned int dst_ofs,
504                  unsigned int n_bits);
505 uint64_t bitwise_get(const void *src, unsigned int src_len,
506                      unsigned int src_ofs, unsigned int n_bits);
507
508 void xsleep(unsigned int seconds);
509
510 #ifdef _WIN32
511 \f
512 char *ovs_format_message(int error);
513 char *ovs_lasterror_to_string(void);
514 int ftruncate(int fd, off_t length);
515 #endif
516
517 #ifdef  __cplusplus
518 }
519 #endif
520
521 #endif /* util.h */