ovn-controller: Handle physical changes correctly
[cascardo/ovs.git] / lib / util.h
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 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 <arpa/inet.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include "compiler.h"
28 #include "openvswitch/util.h"
29
30 extern char *program_name;
31
32 #define __ARRAY_SIZE_NOCHECK(ARRAY) (sizeof(ARRAY) / sizeof((ARRAY)[0]))
33 #ifdef __GNUC__
34 /* return 0 for array types, 1 otherwise */
35 #define __ARRAY_CHECK(ARRAY)                                    \
36     !__builtin_types_compatible_p(typeof(ARRAY), typeof(&ARRAY[0]))
37
38 /* compile-time fail if not array */
39 #define __ARRAY_FAIL(ARRAY) (sizeof(char[-2*!__ARRAY_CHECK(ARRAY)]))
40 #define __ARRAY_SIZE(ARRAY)                                     \
41     __builtin_choose_expr(__ARRAY_CHECK(ARRAY),                 \
42         __ARRAY_SIZE_NOCHECK(ARRAY), __ARRAY_FAIL(ARRAY))
43 #else
44 #define __ARRAY_SIZE(ARRAY) __ARRAY_SIZE_NOCHECK(ARRAY)
45 #endif
46
47
48 /* This system's cache line size, in bytes.
49  * Being wrong hurts performance but not correctness. */
50 #define CACHE_LINE_SIZE 64
51 BUILD_ASSERT_DECL(IS_POW2(CACHE_LINE_SIZE));
52
53 static inline void
54 ovs_prefetch_range(const void *start, size_t size)
55 {
56     const char *addr = (const char *)start;
57     size_t ofs;
58
59     for (ofs = 0; ofs < size; ofs += CACHE_LINE_SIZE) {
60         OVS_PREFETCH(addr + ofs);
61     }
62 }
63
64 #ifndef MIN
65 #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
66 #endif
67
68 #ifndef MAX
69 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
70 #endif
71
72 #define OVS_NOT_REACHED() abort()
73
74 /* Use "%"PRIuSIZE to format size_t with printf(). */
75 #ifdef _WIN32
76 #define PRIdSIZE "Id"
77 #define PRIiSIZE "Ii"
78 #define PRIoSIZE "Io"
79 #define PRIuSIZE "Iu"
80 #define PRIxSIZE "Ix"
81 #define PRIXSIZE "IX"
82 #else
83 #define PRIdSIZE "zd"
84 #define PRIiSIZE "zi"
85 #define PRIoSIZE "zo"
86 #define PRIuSIZE "zu"
87 #define PRIxSIZE "zx"
88 #define PRIXSIZE "zX"
89 #endif
90
91 #ifndef _WIN32
92 typedef uint32_t HANDLE;
93 #endif
94
95 #ifdef  __cplusplus
96 extern "C" {
97 #endif
98
99 #define set_program_name(name) \
100         ovs_set_program_name(name, OVS_PACKAGE_VERSION)
101
102 const char *get_subprogram_name(void);
103     void set_subprogram_name(const char *);
104
105 void ovs_print_version(uint8_t min_ofp, uint8_t max_ofp);
106
107 OVS_NO_RETURN void out_of_memory(void);
108 void *xmalloc(size_t) MALLOC_LIKE;
109 void *xcalloc(size_t, size_t) MALLOC_LIKE;
110 void *xzalloc(size_t) MALLOC_LIKE;
111 void *xrealloc(void *, size_t);
112 void *xmemdup(const void *, size_t) MALLOC_LIKE;
113 char *xmemdup0(const char *, size_t) MALLOC_LIKE;
114 char *xstrdup(const char *) MALLOC_LIKE;
115 char *nullable_xstrdup(const char *) MALLOC_LIKE;
116 char *xasprintf(const char *format, ...) OVS_PRINTF_FORMAT(1, 2) MALLOC_LIKE;
117 char *xvasprintf(const char *format, va_list) OVS_PRINTF_FORMAT(1, 0) MALLOC_LIKE;
118 void *x2nrealloc(void *p, size_t *n, size_t s);
119
120 void *xmalloc_cacheline(size_t) MALLOC_LIKE;
121 void *xzalloc_cacheline(size_t) MALLOC_LIKE;
122 void free_cacheline(void *);
123
124 void ovs_strlcpy(char *dst, const char *src, size_t size);
125 void ovs_strzcpy(char *dst, const char *src, size_t size);
126
127 OVS_NO_RETURN void ovs_abort(int err_no, const char *format, ...)
128     OVS_PRINTF_FORMAT(2, 3);
129 OVS_NO_RETURN void ovs_abort_valist(int err_no, const char *format, va_list)
130     OVS_PRINTF_FORMAT(2, 0);
131 OVS_NO_RETURN void ovs_fatal(int err_no, const char *format, ...)
132     OVS_PRINTF_FORMAT(2, 3);
133 OVS_NO_RETURN void ovs_fatal_valist(int err_no, const char *format, va_list)
134     OVS_PRINTF_FORMAT(2, 0);
135 void ovs_error(int err_no, const char *format, ...) OVS_PRINTF_FORMAT(2, 3);
136 void ovs_error_valist(int err_no, const char *format, va_list)
137     OVS_PRINTF_FORMAT(2, 0);
138 const char *ovs_retval_to_string(int);
139 const char *ovs_strerror(int);
140 void ovs_hex_dump(FILE *, const void *, size_t, uintptr_t offset, bool ascii);
141
142 bool str_to_int(const char *, int base, int *);
143 bool str_to_long(const char *, int base, long *);
144 bool str_to_llong(const char *, int base, long long *);
145 bool str_to_uint(const char *, int base, unsigned int *);
146
147 bool ovs_scan(const char *s, const char *format, ...) OVS_SCANF_FORMAT(2, 3);
148 bool ovs_scan_len(const char *s, int *n, const char *format, ...);
149
150 bool str_to_double(const char *, double *);
151
152 int hexit_value(int c);
153 uintmax_t hexits_value(const char *s, size_t n, bool *ok);
154
155 int parse_int_string(const char *s, uint8_t *valuep, int field_width,
156                      char **tail);
157
158 const char *english_list_delimiter(size_t index, size_t total);
159
160 char *get_cwd(void);
161 #ifndef _WIN32
162 char *dir_name(const char *file_name);
163 char *base_name(const char *file_name);
164 #endif
165 char *abs_file_name(const char *dir, const char *file_name);
166
167 char *follow_symlinks(const char *filename);
168
169 void ignore(bool x OVS_UNUSED);
170 \f
171 /* Bitwise tests. */
172
173 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
174 #if __GNUC__ >= 4
175 static inline int
176 raw_ctz(uint64_t n)
177 {
178     /* With GCC 4.7 on 32-bit x86, if a 32-bit integer is passed as 'n', using
179      * a plain __builtin_ctzll() here always generates an out-of-line function
180      * call.  The test below helps it to emit a single 'bsf' instruction. */
181     return (__builtin_constant_p(n <= UINT32_MAX) && n <= UINT32_MAX
182             ? __builtin_ctz(n)
183             : __builtin_ctzll(n));
184 }
185
186 static inline int
187 raw_clz64(uint64_t n)
188 {
189     return __builtin_clzll(n);
190 }
191 #elif _MSC_VER
192 static inline int
193 raw_ctz(uint64_t n)
194 {
195 #ifdef _WIN64
196     unsigned long r = 0;
197     _BitScanForward64(&r, n);
198     return r;
199 #else
200     unsigned long low = n, high, r = 0;
201     if (_BitScanForward(&r, low)) {
202         return r;
203     }
204     high = n >> 32;
205     _BitScanForward(&r, high);
206     return r + 32;
207 #endif
208 }
209
210 static inline int
211 raw_clz64(uint64_t n)
212 {
213 #ifdef _WIN64
214     unsigned long r = 0;
215     _BitScanReverse64(&r, n);
216     return 63 - r;
217 #else
218     unsigned long low, high = n >> 32, r = 0;
219     if (_BitScanReverse(&r, high)) {
220         return 31 - r;
221     }
222     low = n;
223     _BitScanReverse(&r, low);
224     return 63 - r;
225 #endif
226 }
227 #else
228 /* Defined in util.c. */
229 int raw_ctz(uint64_t n);
230 int raw_clz64(uint64_t n);
231 #endif
232
233 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
234 static inline int
235 ctz32(uint32_t n)
236 {
237     return n ? raw_ctz(n) : 32;
238 }
239
240 /* Returns the number of trailing 0-bits in 'n', or 64 if 'n' is 0. */
241 static inline int
242 ctz64(uint64_t n)
243 {
244     return n ? raw_ctz(n) : 64;
245 }
246
247 /* Returns the number of leading 0-bits in 'n', or 32 if 'n' is 0. */
248 static inline int
249 clz32(uint32_t n)
250 {
251     return n ? raw_clz64(n) - 32 : 32;
252 }
253
254 /* Returns the number of leading 0-bits in 'n', or 64 if 'n' is 0. */
255 static inline int
256 clz64(uint64_t n)
257 {
258     return n ? raw_clz64(n) : 64;
259 }
260
261 /* Given a word 'n', calculates floor(log_2('n')).  This is equivalent
262  * to finding the bit position of the most significant one bit in 'n'.  It is
263  * an error to call this function with 'n' == 0. */
264 static inline int
265 log_2_floor(uint64_t n)
266 {
267     return 63 - raw_clz64(n);
268 }
269
270 /* Given a word 'n', calculates ceil(log_2('n')).  It is an error to
271  * call this function with 'n' == 0. */
272 static inline int
273 log_2_ceil(uint64_t n)
274 {
275     return log_2_floor(n) + !is_pow2(n);
276 }
277
278 /* unsigned int count_1bits(uint64_t x):
279  *
280  * Returns the number of 1-bits in 'x', between 0 and 64 inclusive. */
281 #if UINTPTR_MAX == UINT64_MAX
282 static inline unsigned int
283 count_1bits(uint64_t x)
284 {
285 #if __GNUC__ >= 4 && __POPCNT__
286     return __builtin_popcountll(x);
287 #else
288     /* This portable implementation is the fastest one we know of for 64
289      * bits, and about 3x faster than GCC 4.7 __builtin_popcountll(). */
290     const uint64_t h55 = UINT64_C(0x5555555555555555);
291     const uint64_t h33 = UINT64_C(0x3333333333333333);
292     const uint64_t h0F = UINT64_C(0x0F0F0F0F0F0F0F0F);
293     const uint64_t h01 = UINT64_C(0x0101010101010101);
294     x -= (x >> 1) & h55;               /* Count of each 2 bits in-place. */
295     x = (x & h33) + ((x >> 2) & h33);  /* Count of each 4 bits in-place. */
296     x = (x + (x >> 4)) & h0F;          /* Count of each 8 bits in-place. */
297     return (x * h01) >> 56;            /* Sum of all bytes. */
298 #endif
299 }
300 #else /* Not 64-bit. */
301 #if __GNUC__ >= 4 && __POPCNT__
302 static inline unsigned int
303 count_1bits_32__(uint32_t x)
304 {
305     return __builtin_popcount(x);
306 }
307 #else
308 #define NEED_COUNT_1BITS_8 1
309 extern const uint8_t count_1bits_8[256];
310 static inline unsigned int
311 count_1bits_32__(uint32_t x)
312 {
313     /* This portable implementation is the fastest one we know of for 32 bits,
314      * and faster than GCC __builtin_popcount(). */
315     return (count_1bits_8[x & 0xff] +
316             count_1bits_8[(x >> 8) & 0xff] +
317             count_1bits_8[(x >> 16) & 0xff] +
318             count_1bits_8[x >> 24]);
319 }
320 #endif
321 static inline unsigned int
322 count_1bits(uint64_t x)
323 {
324     return count_1bits_32__(x) + count_1bits_32__(x >> 32);
325 }
326 #endif
327
328 /* Returns the rightmost 1-bit in 'x' (e.g. 01011000 => 00001000), or 0 if 'x'
329  * is 0. */
330 static inline uintmax_t
331 rightmost_1bit(uintmax_t x)
332 {
333     return x & -x;
334 }
335
336 /* Returns 'x' with its rightmost 1-bit changed to a zero (e.g. 01011000 =>
337  * 01010000), or 0 if 'x' is 0. */
338 static inline uintmax_t
339 zero_rightmost_1bit(uintmax_t x)
340 {
341     return x & (x - 1);
342 }
343
344 /* Returns the index of the rightmost 1-bit in 'x' (e.g. 01011000 => 3), or an
345  * undefined value if 'x' is 0. */
346 static inline int
347 rightmost_1bit_idx(uint64_t x)
348 {
349     return ctz64(x);
350 }
351
352 /* Returns the index of the leftmost 1-bit in 'x' (e.g. 01011000 => 6), or an
353  * undefined value if 'x' is 0. */
354 static inline uint32_t
355 leftmost_1bit_idx(uint64_t x)
356 {
357     return log_2_floor(x);
358 }
359
360 /* Return a ovs_be32 prefix in network byte order with 'plen' highest bits set.
361  * Shift with 32 is undefined behavior, but we rather use 64-bit shift than
362  * compare. */
363 static inline ovs_be32 be32_prefix_mask(int plen)
364 {
365     return htonl((uint64_t)UINT32_MAX << (32 - plen));
366 }
367 \f
368 bool is_all_zeros(const void *, size_t);
369 bool is_all_ones(const void *, size_t);
370 void bitwise_copy(const void *src, unsigned int src_len, unsigned int src_ofs,
371                   void *dst, unsigned int dst_len, unsigned int dst_ofs,
372                   unsigned int n_bits);
373 void bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
374                   unsigned int n_bits);
375 void bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
376                  unsigned int n_bits);
377 bool bitwise_is_all_zeros(const void *, unsigned int len, unsigned int ofs,
378                           unsigned int n_bits);
379 unsigned int bitwise_scan(const void *, unsigned int len,
380                           bool target, unsigned int start, unsigned int end);
381 int bitwise_rscan(const void *, unsigned int len, bool target,
382                   int start, int end);
383 void bitwise_put(uint64_t value,
384                  void *dst, unsigned int dst_len, unsigned int dst_ofs,
385                  unsigned int n_bits);
386 uint64_t bitwise_get(const void *src, unsigned int src_len,
387                      unsigned int src_ofs, unsigned int n_bits);
388 bool bitwise_get_bit(const void *src, unsigned int len, unsigned int ofs);
389 void bitwise_put0(void *dst, unsigned int len, unsigned int ofs);
390 void bitwise_put1(void *dst, unsigned int len, unsigned int ofs);
391 void bitwise_put_bit(void *dst, unsigned int len, unsigned int ofs, bool);
392 void bitwise_toggle_bit(void *dst, unsigned int len, unsigned int ofs);
393
394 /* Returns non-zero if the parameters have equal value. */
395 static inline int
396 ovs_u128_equals(const ovs_u128 a, const ovs_u128 b)
397 {
398     return (a.u64.hi == b.u64.hi) && (a.u64.lo == b.u64.lo);
399 }
400
401 /* Returns true if 'val' is 0. */
402 static inline bool
403 ovs_u128_is_zero(const ovs_u128 val)
404 {
405     return !(val.u64.hi || val.u64.lo);
406 }
407
408 /* Returns true if 'val' is all ones. */
409 static inline bool
410 ovs_u128_is_ones(const ovs_u128 val)
411 {
412     return ovs_u128_equals(val, OVS_U128_MAX);
413 }
414
415 /* Returns non-zero if the parameters have equal value. */
416 static inline int
417 ovs_be128_equals(const ovs_be128 a, const ovs_be128 b)
418 {
419     return (a.be64.hi == b.be64.hi) && (a.be64.lo == b.be64.lo);
420 }
421
422 /* Returns true if 'val' is 0. */
423 static inline bool
424 ovs_be128_is_zero(const ovs_be128 val)
425 {
426     return !(val.be64.hi || val.be64.lo);
427 }
428
429 static inline ovs_u128
430 ovs_u128_and(const ovs_u128 a, const ovs_u128 b)
431 {
432     ovs_u128 dst;
433
434     dst.u64.hi = a.u64.hi & b.u64.hi;
435     dst.u64.lo = a.u64.lo & b.u64.lo;
436
437     return dst;
438 }
439
440 void xsleep(unsigned int seconds);
441
442 bool is_stdout_a_tty(void);
443
444 #ifdef _WIN32
445 \f
446 char *ovs_format_message(int error);
447 char *ovs_lasterror_to_string(void);
448 int ftruncate(int fd, off_t length);
449 #endif
450
451 #ifdef  __cplusplus
452 }
453 #endif
454
455 #endif /* util.h */