2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
29 #include "byte-order.h"
31 #include "ovs-thread.h"
34 VLOG_DEFINE_THIS_MODULE(util);
36 COVERAGE_DEFINE(util_xalloc);
38 /* argv[0] without directory names. */
39 const char *program_name;
41 /* Name for the currently running thread or process, for log messages, process
42 * listings, and debuggers. */
43 DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name);
45 /* --version option output. */
46 static char *program_version;
48 /* Buffer used by ovs_strerror(). */
49 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
54 ovs_assert_failure(const char *where, const char *function,
55 const char *condition)
57 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
58 * to trigger an assertion failure of its own. */
59 static int reentry = 0;
63 VLOG_ABORT("%s: assertion %s failed in %s()",
64 where, condition, function);
68 fprintf(stderr, "%s: assertion %s failed in %s()",
69 where, condition, function);
80 ovs_abort(0, "virtual memory exhausted");
84 xcalloc(size_t count, size_t size)
86 void *p = count && size ? calloc(count, size) : malloc(1);
87 COVERAGE_INC(util_xalloc);
97 return xcalloc(1, size);
103 void *p = malloc(size ? size : 1);
104 COVERAGE_INC(util_xalloc);
112 xrealloc(void *p, size_t size)
114 p = realloc(p, size ? size : 1);
115 COVERAGE_INC(util_xalloc);
123 xmemdup(const void *p_, size_t size)
125 void *p = xmalloc(size);
131 xmemdup0(const char *p_, size_t length)
133 char *p = xmalloc(length + 1);
134 memcpy(p, p_, length);
140 xstrdup(const char *s)
142 return xmemdup0(s, strlen(s));
146 xvasprintf(const char *format, va_list args)
152 va_copy(args2, args);
153 needed = vsnprintf(NULL, 0, format, args);
155 s = xmalloc(needed + 1);
157 vsnprintf(s, needed + 1, format, args2);
164 x2nrealloc(void *p, size_t *n, size_t s)
166 *n = *n == 0 ? 1 : 2 * *n;
167 return xrealloc(p, *n * s);
171 xasprintf(const char *format, ...)
176 va_start(args, format);
177 s = xvasprintf(format, args);
183 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
184 * bytes from 'src' and doesn't return anything. */
186 ovs_strlcpy(char *dst, const char *src, size_t size)
189 size_t len = strnlen(src, size - 1);
190 memcpy(dst, src, len);
195 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
196 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
197 * to every otherwise unused byte in 'dst'.
199 * Except for performance, the following call:
200 * ovs_strzcpy(dst, src, size);
201 * is equivalent to these two calls:
202 * memset(dst, '\0', size);
203 * ovs_strlcpy(dst, src, size);
205 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
208 ovs_strzcpy(char *dst, const char *src, size_t size)
211 size_t len = strnlen(src, size - 1);
212 memcpy(dst, src, len);
213 memset(dst + len, '\0', size - len);
217 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
218 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
219 * the message inside parentheses. Then, terminates with abort().
221 * This function is preferred to ovs_fatal() in a situation where it would make
222 * sense for a monitoring process to restart the daemon.
224 * 'format' should not end with a new-line, because this function will add one
227 ovs_abort(int err_no, const char *format, ...)
231 va_start(args, format);
232 ovs_abort_valist(err_no, format, args);
235 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
237 ovs_abort_valist(int err_no, const char *format, va_list args)
239 ovs_error_valist(err_no, format, args);
243 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
244 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
245 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
247 * 'format' should not end with a new-line, because this function will add one
250 ovs_fatal(int err_no, const char *format, ...)
254 va_start(args, format);
255 ovs_fatal_valist(err_no, format, args);
258 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
260 ovs_fatal_valist(int err_no, const char *format, va_list args)
262 ovs_error_valist(err_no, format, args);
266 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
267 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
268 * the message inside parentheses.
270 * 'format' should not end with a new-line, because this function will add one
273 ovs_error(int err_no, const char *format, ...)
277 va_start(args, format);
278 ovs_error_valist(err_no, format, args);
282 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
284 ovs_error_valist(int err_no, const char *format, va_list args)
286 const char *subprogram_name = get_subprogram_name();
287 int save_errno = errno;
289 if (subprogram_name[0]) {
290 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
292 fprintf(stderr, "%s: ", program_name);
295 vfprintf(stderr, format, args);
297 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
304 /* Many OVS functions return an int which is one of:
307 * - EOF: end of file (not necessarily an error; depends on the function called)
309 * Returns the appropriate human-readable string. The caller must copy the
310 * string if it wants to hold onto it, as the storage may be overwritten on
311 * subsequent function calls.
314 ovs_retval_to_string(int retval)
317 : retval == EOF ? "End of file"
318 : ovs_strerror(retval));
322 ovs_strerror(int error)
324 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
330 buffer = strerror_buffer_get()->s;
332 #if STRERROR_R_CHAR_P
333 /* GNU style strerror_r() might return an immutable static string, or it
334 * might write and return 'buffer', but in either case we can pass the
335 * returned string directly to the caller. */
336 s = strerror_r(error, buffer, BUFSIZE);
337 #else /* strerror_r() returns an int. */
339 if (strerror_r(error, buffer, BUFSIZE)) {
340 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
341 * is too short). We don't check the actual failure reason because
342 * POSIX requires strerror_r() to return the error but old glibc
343 * (before 2.13) returns -1 and sets errno. */
344 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
353 /* Sets global "program_name" and "program_version" variables. Should
354 * be called at the beginning of main() with "argv[0]" as the argument
357 * 'version' should contain the version of the caller's program. If 'version'
358 * is the same as the VERSION #define, the caller is assumed to be part of Open
359 * vSwitch. Otherwise, it is assumed to be an external program linking against
360 * the Open vSwitch libraries.
362 * The 'date' and 'time' arguments should likely be called with
363 * "__DATE__" and "__TIME__" to use the time the binary was built.
364 * Alternatively, the "set_program_name" macro may be called to do this
368 set_program_name__(const char *argv0, const char *version, const char *date,
371 const char *slash = strrchr(argv0, '/');
373 assert_single_threaded();
375 program_name = slash ? slash + 1 : argv0;
377 free(program_version);
379 if (!strcmp(version, VERSION)) {
380 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
382 program_name, date, time);
384 program_version = xasprintf("%s %s\n"
385 "Open vSwitch Library "VERSION"\n"
387 program_name, version, date, time);
391 /* Returns the name of the currently running thread or process. */
393 get_subprogram_name(void)
395 const char *name = subprogram_name_get();
396 return name ? name : "";
399 /* Sets 'name' as the name of the currently running thread or process. (This
400 * appears in log messages and may also be visible in system process listings
403 set_subprogram_name(const char *name)
405 free(subprogram_name_set(xstrdup(name)));
406 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
407 pthread_setname_np(pthread_self(), name);
408 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
409 pthread_setname_np(pthread_self(), "%s", name);
410 #elif HAVE_PTHREAD_SET_NAME_NP
411 pthread_set_name_np(pthread_self(), name);
415 /* Returns a pointer to a string describing the program version. The
416 * caller must not modify or free the returned string.
419 get_program_version(void)
421 return program_version;
424 /* Print the version information for the program. */
426 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
428 printf("%s", program_version);
429 if (min_ofp || max_ofp) {
430 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
434 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
435 * line. Numeric offsets are also included, starting at 'ofs' for the first
436 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
437 * are also rendered alongside. */
439 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
440 uintptr_t ofs, bool ascii)
442 const uint8_t *buf = buf_;
443 const size_t per_line = 16; /* Maximum bytes per line. */
447 size_t start, end, n;
450 /* Number of bytes on this line. */
451 start = ofs % per_line;
453 if (end - start > size)
458 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
459 for (i = 0; i < start; i++)
460 fprintf(stream, " ");
462 fprintf(stream, "%02hhx%c",
463 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
466 for (; i < per_line; i++)
467 fprintf(stream, " ");
468 fprintf(stream, "|");
469 for (i = 0; i < start; i++)
470 fprintf(stream, " ");
471 for (; i < end; i++) {
472 int c = buf[i - start];
473 putc(c >= 32 && c < 127 ? c : '.', stream);
475 for (; i < per_line; i++)
476 fprintf(stream, " ");
477 fprintf(stream, "|");
479 fprintf(stream, "\n");
488 str_to_int(const char *s, int base, int *i)
491 bool ok = str_to_llong(s, base, &ll);
497 str_to_long(const char *s, int base, long *li)
500 bool ok = str_to_llong(s, base, &ll);
506 str_to_llong(const char *s, int base, long long *x)
508 int save_errno = errno;
511 *x = strtoll(s, &tail, base);
512 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
523 str_to_uint(const char *s, int base, unsigned int *u)
525 return str_to_int(s, base, (int *) u);
529 str_to_ulong(const char *s, int base, unsigned long *ul)
531 return str_to_long(s, base, (long *) ul);
535 str_to_ullong(const char *s, int base, unsigned long long *ull)
537 return str_to_llong(s, base, (long long *) ull);
540 /* Converts floating-point string 's' into a double. If successful, stores
541 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
544 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
545 * (e.g. "1e9999)" is. */
547 str_to_double(const char *s, double *d)
549 int save_errno = errno;
552 *d = strtod(s, &tail);
553 if (errno == EINVAL || (errno == ERANGE && *d != 0)
554 || tail == s || *tail != '\0') {
564 /* Returns the value of 'c' as a hexadecimal digit. */
569 case '0': case '1': case '2': case '3': case '4':
570 case '5': case '6': case '7': case '8': case '9':
596 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
597 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
598 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
599 * non-hex digit is detected. */
601 hexits_value(const char *s, size_t n, bool *ok)
607 for (i = 0; i < n; i++) {
608 int hexit = hexit_value(s[i]);
615 value = (value << 4) + hexit;
623 /* Returns the current working directory as a malloc()'d string, or a null
624 * pointer if the current working directory cannot be determined. */
631 /* Get maximum path length or at least a reasonable estimate. */
632 path_max = pathconf(".", _PC_PATH_MAX);
633 size = (path_max < 0 ? 1024
634 : path_max > 10240 ? 10240
637 /* Get current working directory. */
639 char *buf = xmalloc(size);
640 if (getcwd(buf, size)) {
641 return xrealloc(buf, strlen(buf) + 1);
645 if (error != ERANGE) {
646 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
655 all_slashes_name(const char *s)
657 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
662 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
663 * similar to the POSIX dirname() function but thread-safe. */
665 dir_name(const char *file_name)
667 size_t len = strlen(file_name);
668 while (len > 0 && file_name[len - 1] == '/') {
671 while (len > 0 && file_name[len - 1] != '/') {
674 while (len > 0 && file_name[len - 1] == '/') {
677 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
680 /* Returns the file name portion of 'file_name' as a malloc()'d string,
681 * similar to the POSIX basename() function but thread-safe. */
683 base_name(const char *file_name)
687 end = strlen(file_name);
688 while (end > 0 && file_name[end - 1] == '/') {
693 return all_slashes_name(file_name);
697 while (start > 0 && file_name[start - 1] != '/') {
701 return xmemdup0(file_name + start, end - start);
704 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
705 * returns an absolute path to 'file_name' considering it relative to 'dir',
706 * which itself must be absolute. 'dir' may be null or the empty string, in
707 * which case the current working directory is used.
709 * Returns a null pointer if 'dir' is null and getcwd() fails. */
711 abs_file_name(const char *dir, const char *file_name)
713 if (file_name[0] == '/') {
714 return xstrdup(file_name);
715 } else if (dir && dir[0]) {
716 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
717 return xasprintf("%s%s%s", dir, separator, file_name);
719 char *cwd = get_cwd();
721 char *abs_name = xasprintf("%s/%s", cwd, file_name);
730 /* Like readlink(), but returns the link name as a null-terminated string in
731 * allocated memory that the caller must eventually free (with free()).
732 * Returns NULL on error, in which case errno is set appropriately. */
734 xreadlink(const char *filename)
738 for (size = 64; ; size *= 2) {
739 char *buf = xmalloc(size);
740 ssize_t retval = readlink(filename, buf, size);
743 if (retval >= 0 && retval < size) {
756 /* Returns a version of 'filename' with symlinks in the final component
757 * dereferenced. This differs from realpath() in that:
759 * - 'filename' need not exist.
761 * - If 'filename' does exist as a symlink, its referent need not exist.
763 * - Only symlinks in the final component of 'filename' are dereferenced.
765 * The caller must eventually free the returned string (with free()). */
767 follow_symlinks(const char *filename)
773 fn = xstrdup(filename);
774 for (i = 0; i < 10; i++) {
778 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
782 linkname = xreadlink(fn);
784 VLOG_WARN("%s: readlink failed (%s)",
785 filename, ovs_strerror(errno));
789 if (linkname[0] == '/') {
790 /* Target of symlink is absolute so use it raw. */
793 /* Target of symlink is relative so add to 'fn''s directory. */
794 char *dir = dir_name(fn);
796 if (!strcmp(dir, ".")) {
799 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
800 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
811 VLOG_WARN("%s: too many levels of symlinks", filename);
813 return xstrdup(filename);
816 /* Pass a value to this function if it is marked with
817 * __attribute__((warn_unused_result)) and you genuinely want to ignore
818 * its return value. (Note that every scalar type can be implicitly
819 * converted to bool.) */
820 void ignore(bool x OVS_UNUSED) { }
822 /* Returns an appropriate delimiter for inserting just before the 0-based item
823 * 'index' in a list that has 'total' items in it. */
825 english_list_delimiter(size_t index, size_t total)
827 return (index == 0 ? ""
828 : index < total - 1 ? ", "
829 : total > 2 ? ", and "
833 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
834 * to finding the bit position of the most significant one bit in 'n'. It is
835 * an error to call this function with 'n' == 0. */
837 log_2_floor(uint32_t n)
841 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
842 #error "Someone screwed up the #includes."
843 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
844 return 31 - __builtin_clz(n);
849 #define BIN_SEARCH_STEP(BITS) \
850 if (n >= (1 << BITS)) { \
859 #undef BIN_SEARCH_STEP
865 /* Given a 32 bit word 'n', calculates ceil(log_2('n')). It is an error to
866 * call this function with 'n' == 0. */
868 log_2_ceil(uint32_t n)
870 return log_2_floor(n) + !is_pow2(n);
873 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
874 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
875 #error "Someone screwed up the #includes."
876 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
877 /* Defined inline in util.h. */
885 #define CTZ_STEP(X) \
902 /* Returns the number of 1-bits in 'x', between 0 and 32 inclusive. */
906 /* In my testing, this implementation is over twice as fast as any other
907 * portable implementation that I tried, including GCC 4.4
908 * __builtin_popcount(), although nonportable asm("popcnt") was over 50%
911 ((((X) & (1 << 0)) != 0) + \
912 (((X) & (1 << 1)) != 0) + \
913 (((X) & (1 << 2)) != 0) + \
914 (((X) & (1 << 3)) != 0) + \
915 (((X) & (1 << 4)) != 0) + \
916 (((X) & (1 << 5)) != 0) + \
917 (((X) & (1 << 6)) != 0) + \
918 (((X) & (1 << 7)) != 0))
919 #define INIT2(X) INIT1(X), INIT1((X) + 1)
920 #define INIT4(X) INIT2(X), INIT2((X) + 2)
921 #define INIT8(X) INIT4(X), INIT4((X) + 4)
922 #define INIT16(X) INIT8(X), INIT8((X) + 8)
923 #define INIT32(X) INIT16(X), INIT16((X) + 16)
924 #define INIT64(X) INIT32(X), INIT32((X) + 32)
926 static const uint8_t popcount8[256] = {
927 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
930 return (popcount8[x & 0xff] +
931 popcount8[(x >> 8) & 0xff] +
932 popcount8[(x >> 16) & 0xff] +
936 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
938 is_all_zeros(const uint8_t *p, size_t n)
942 for (i = 0; i < n; i++) {
950 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
952 is_all_ones(const uint8_t *p, size_t n)
956 for (i = 0; i < n; i++) {
964 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
965 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
966 * 'dst' is 'dst_len' bytes long.
968 * If you consider all of 'src' to be a single unsigned integer in network byte
969 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
970 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
971 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
972 * 2], and so on. Similarly for 'dst'.
974 * Required invariants:
975 * src_ofs + n_bits <= src_len * 8
976 * dst_ofs + n_bits <= dst_len * 8
977 * 'src' and 'dst' must not overlap.
980 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
981 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
984 const uint8_t *src = src_;
987 src += src_len - (src_ofs / 8 + 1);
990 dst += dst_len - (dst_ofs / 8 + 1);
993 if (src_ofs == 0 && dst_ofs == 0) {
994 unsigned int n_bytes = n_bits / 8;
998 memcpy(dst, src, n_bytes);
1005 uint8_t mask = (1 << n_bits) - 1;
1006 *dst = (*dst & ~mask) | (*src & mask);
1009 while (n_bits > 0) {
1010 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1011 unsigned int chunk = MIN(n_bits, max_copy);
1012 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1015 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1032 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1033 * 'dst_len' bytes long.
1035 * If you consider all of 'dst' to be a single unsigned integer in network byte
1036 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1037 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1038 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1041 * Required invariant:
1042 * dst_ofs + n_bits <= dst_len * 8
1045 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1046 unsigned int n_bits)
1048 uint8_t *dst = dst_;
1054 dst += dst_len - (dst_ofs / 8 + 1);
1058 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1060 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1070 while (n_bits >= 8) {
1076 *dst &= ~((1 << n_bits) - 1);
1080 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1081 * 'dst' is 'dst_len' bytes long.
1083 * If you consider all of 'dst' to be a single unsigned integer in network byte
1084 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1085 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1086 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1089 * Required invariant:
1090 * dst_ofs + n_bits <= dst_len * 8
1093 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1094 unsigned int n_bits)
1096 uint8_t *dst = dst_;
1102 dst += dst_len - (dst_ofs / 8 + 1);
1106 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1108 *dst |= ((1 << chunk) - 1) << dst_ofs;
1118 while (n_bits >= 8) {
1124 *dst |= (1 << n_bits) - 1;
1128 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1129 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1132 * If you consider all of 'dst' to be a single unsigned integer in network byte
1133 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1134 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1135 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1138 * Required invariant:
1139 * dst_ofs + n_bits <= dst_len * 8
1142 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1143 unsigned int n_bits)
1145 const uint8_t *p = p_;
1151 p += len - (ofs / 8 + 1);
1155 unsigned int chunk = MIN(n_bits, 8 - ofs);
1157 if (*p & (((1 << chunk) - 1) << ofs)) {
1169 while (n_bits >= 8) {
1177 if (n_bits && *p & ((1 << n_bits) - 1)) {
1184 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1185 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1187 * If you consider all of 'dst' to be a single unsigned integer in network byte
1188 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1189 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1190 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1193 * Required invariants:
1194 * dst_ofs + n_bits <= dst_len * 8
1198 bitwise_put(uint64_t value,
1199 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1200 unsigned int n_bits)
1202 ovs_be64 n_value = htonll(value);
1203 bitwise_copy(&n_value, sizeof n_value, 0,
1204 dst, dst_len, dst_ofs,
1208 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1209 * which is 'src_len' bytes long.
1211 * If you consider all of 'src' to be a single unsigned integer in network byte
1212 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1213 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1214 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1217 * Required invariants:
1218 * src_ofs + n_bits <= src_len * 8
1222 bitwise_get(const void *src, unsigned int src_len,
1223 unsigned int src_ofs, unsigned int n_bits)
1225 ovs_be64 value = htonll(0);
1227 bitwise_copy(src, src_len, src_ofs,
1228 &value, sizeof value, 0,
1230 return ntohll(value);