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_PER_THREAD_DATA(struct { char s[128]; }, strerror_buffer, { "" });
52 ovs_assert_failure(const char *where, const char *function,
53 const char *condition)
55 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
56 * to trigger an assertion failure of its own. */
57 static int reentry = 0;
61 VLOG_ABORT("%s: assertion %s failed in %s()",
62 where, condition, function);
66 fprintf(stderr, "%s: assertion %s failed in %s()",
67 where, condition, function);
78 ovs_abort(0, "virtual memory exhausted");
82 xcalloc(size_t count, size_t size)
84 void *p = count && size ? calloc(count, size) : malloc(1);
85 COVERAGE_INC(util_xalloc);
95 return xcalloc(1, size);
101 void *p = malloc(size ? size : 1);
102 COVERAGE_INC(util_xalloc);
110 xrealloc(void *p, size_t size)
112 p = realloc(p, size ? size : 1);
113 COVERAGE_INC(util_xalloc);
121 xmemdup(const void *p_, size_t size)
123 void *p = xmalloc(size);
129 xmemdup0(const char *p_, size_t length)
131 char *p = xmalloc(length + 1);
132 memcpy(p, p_, length);
138 xstrdup(const char *s)
140 return xmemdup0(s, strlen(s));
144 xvasprintf(const char *format, va_list args)
150 va_copy(args2, args);
151 needed = vsnprintf(NULL, 0, format, args);
153 s = xmalloc(needed + 1);
155 vsnprintf(s, needed + 1, format, args2);
162 x2nrealloc(void *p, size_t *n, size_t s)
164 *n = *n == 0 ? 1 : 2 * *n;
165 return xrealloc(p, *n * s);
169 xasprintf(const char *format, ...)
174 va_start(args, format);
175 s = xvasprintf(format, args);
181 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
182 * bytes from 'src' and doesn't return anything. */
184 ovs_strlcpy(char *dst, const char *src, size_t size)
187 size_t len = strnlen(src, size - 1);
188 memcpy(dst, src, len);
193 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
194 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
195 * to every otherwise unused byte in 'dst'.
197 * Except for performance, the following call:
198 * ovs_strzcpy(dst, src, size);
199 * is equivalent to these two calls:
200 * memset(dst, '\0', size);
201 * ovs_strlcpy(dst, src, size);
203 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
206 ovs_strzcpy(char *dst, const char *src, size_t size)
209 size_t len = strnlen(src, size - 1);
210 memcpy(dst, src, len);
211 memset(dst + len, '\0', size - len);
215 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
216 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
217 * the message inside parentheses. Then, terminates with abort().
219 * This function is preferred to ovs_fatal() in a situation where it would make
220 * sense for a monitoring process to restart the daemon.
222 * 'format' should not end with a new-line, because this function will add one
225 ovs_abort(int err_no, const char *format, ...)
229 va_start(args, format);
230 ovs_abort_valist(err_no, format, args);
233 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
235 ovs_abort_valist(int err_no, const char *format, va_list args)
237 ovs_error_valist(err_no, format, args);
241 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
242 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
243 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
245 * 'format' should not end with a new-line, because this function will add one
248 ovs_fatal(int err_no, const char *format, ...)
252 va_start(args, format);
253 ovs_fatal_valist(err_no, format, args);
256 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
258 ovs_fatal_valist(int err_no, const char *format, va_list args)
260 ovs_error_valist(err_no, format, args);
264 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
265 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
266 * the message inside parentheses.
268 * 'format' should not end with a new-line, because this function will add one
271 ovs_error(int err_no, const char *format, ...)
275 va_start(args, format);
276 ovs_error_valist(err_no, format, args);
280 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
282 ovs_error_valist(int err_no, const char *format, va_list args)
284 const char *subprogram_name = get_subprogram_name();
285 int save_errno = errno;
287 if (subprogram_name[0]) {
288 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
290 fprintf(stderr, "%s: ", program_name);
293 vfprintf(stderr, format, args);
295 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
302 /* Many OVS functions return an int which is one of:
305 * - EOF: end of file (not necessarily an error; depends on the function called)
307 * Returns the appropriate human-readable string. The caller must copy the
308 * string if it wants to hold onto it, as the storage may be overwritten on
309 * subsequent function calls.
312 ovs_retval_to_string(int retval)
315 : retval == EOF ? "End of file"
316 : ovs_strerror(retval));
320 ovs_strerror(int error)
322 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
328 buffer = strerror_buffer_get()->s;
330 #if STRERROR_R_CHAR_P
331 /* GNU style strerror_r() might return an immutable static string, or it
332 * might write and return 'buffer', but in either case we can pass the
333 * returned string directly to the caller. */
334 s = strerror_r(error, buffer, BUFSIZE);
335 #else /* strerror_r() returns an int. */
337 if (strerror_r(error, buffer, BUFSIZE)) {
338 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
339 * is too short). We don't check the actual failure reason because
340 * POSIX requires strerror_r() to return the error but old glibc
341 * (before 2.13) returns -1 and sets errno. */
342 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
351 /* Sets global "program_name" and "program_version" variables. Should
352 * be called at the beginning of main() with "argv[0]" as the argument
355 * 'version' should contain the version of the caller's program. If 'version'
356 * is the same as the VERSION #define, the caller is assumed to be part of Open
357 * vSwitch. Otherwise, it is assumed to be an external program linking against
358 * the Open vSwitch libraries.
360 * The 'date' and 'time' arguments should likely be called with
361 * "__DATE__" and "__TIME__" to use the time the binary was built.
362 * Alternatively, the "set_program_name" macro may be called to do this
366 set_program_name__(const char *argv0, const char *version, const char *date,
369 const char *slash = strrchr(argv0, '/');
371 assert_single_threaded();
373 program_name = slash ? slash + 1 : argv0;
375 free(program_version);
377 if (!strcmp(version, VERSION)) {
378 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
380 program_name, date, time);
382 program_version = xasprintf("%s %s\n"
383 "Open vSwitch Library "VERSION"\n"
385 program_name, version, date, time);
389 /* Returns the name of the currently running thread or process. */
391 get_subprogram_name(void)
393 const char *name = subprogram_name_get();
394 return name ? name : "";
397 /* Sets 'name' as the name of the currently running thread or process. (This
398 * appears in log messages and may also be visible in system process listings
401 set_subprogram_name(const char *name)
403 free(subprogram_name_set(xstrdup(name)));
404 #if HAVE_PTHREAD_SETNAME_NP
405 pthread_setname_np(pthread_self(), name);
406 #elif HAVE_PTHREAD_SET_NAME_NP
407 pthread_set_name_np(pthread_self(), name);
411 /* Returns a pointer to a string describing the program version. The
412 * caller must not modify or free the returned string.
415 get_program_version(void)
417 return program_version;
420 /* Print the version information for the program. */
422 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
424 printf("%s", program_version);
425 if (min_ofp || max_ofp) {
426 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
430 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
431 * line. Numeric offsets are also included, starting at 'ofs' for the first
432 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
433 * are also rendered alongside. */
435 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
436 uintptr_t ofs, bool ascii)
438 const uint8_t *buf = buf_;
439 const size_t per_line = 16; /* Maximum bytes per line. */
443 size_t start, end, n;
446 /* Number of bytes on this line. */
447 start = ofs % per_line;
449 if (end - start > size)
454 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
455 for (i = 0; i < start; i++)
456 fprintf(stream, " ");
458 fprintf(stream, "%02hhx%c",
459 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
462 for (; i < per_line; i++)
463 fprintf(stream, " ");
464 fprintf(stream, "|");
465 for (i = 0; i < start; i++)
466 fprintf(stream, " ");
467 for (; i < end; i++) {
468 int c = buf[i - start];
469 putc(c >= 32 && c < 127 ? c : '.', stream);
471 for (; i < per_line; i++)
472 fprintf(stream, " ");
473 fprintf(stream, "|");
475 fprintf(stream, "\n");
484 str_to_int(const char *s, int base, int *i)
487 bool ok = str_to_llong(s, base, &ll);
493 str_to_long(const char *s, int base, long *li)
496 bool ok = str_to_llong(s, base, &ll);
502 str_to_llong(const char *s, int base, long long *x)
504 int save_errno = errno;
507 *x = strtoll(s, &tail, base);
508 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
519 str_to_uint(const char *s, int base, unsigned int *u)
521 return str_to_int(s, base, (int *) u);
525 str_to_ulong(const char *s, int base, unsigned long *ul)
527 return str_to_long(s, base, (long *) ul);
531 str_to_ullong(const char *s, int base, unsigned long long *ull)
533 return str_to_llong(s, base, (long long *) ull);
536 /* Converts floating-point string 's' into a double. If successful, stores
537 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
540 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
541 * (e.g. "1e9999)" is. */
543 str_to_double(const char *s, double *d)
545 int save_errno = errno;
548 *d = strtod(s, &tail);
549 if (errno == EINVAL || (errno == ERANGE && *d != 0)
550 || tail == s || *tail != '\0') {
560 /* Returns the value of 'c' as a hexadecimal digit. */
565 case '0': case '1': case '2': case '3': case '4':
566 case '5': case '6': case '7': case '8': case '9':
592 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
593 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
594 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
595 * non-hex digit is detected. */
597 hexits_value(const char *s, size_t n, bool *ok)
603 for (i = 0; i < n; i++) {
604 int hexit = hexit_value(s[i]);
611 value = (value << 4) + hexit;
619 /* Returns the current working directory as a malloc()'d string, or a null
620 * pointer if the current working directory cannot be determined. */
627 /* Get maximum path length or at least a reasonable estimate. */
628 path_max = pathconf(".", _PC_PATH_MAX);
629 size = (path_max < 0 ? 1024
630 : path_max > 10240 ? 10240
633 /* Get current working directory. */
635 char *buf = xmalloc(size);
636 if (getcwd(buf, size)) {
637 return xrealloc(buf, strlen(buf) + 1);
641 if (error != ERANGE) {
642 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
651 all_slashes_name(const char *s)
653 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
658 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
659 * similar to the POSIX dirname() function but thread-safe. */
661 dir_name(const char *file_name)
663 size_t len = strlen(file_name);
664 while (len > 0 && file_name[len - 1] == '/') {
667 while (len > 0 && file_name[len - 1] != '/') {
670 while (len > 0 && file_name[len - 1] == '/') {
673 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
676 /* Returns the file name portion of 'file_name' as a malloc()'d string,
677 * similar to the POSIX basename() function but thread-safe. */
679 base_name(const char *file_name)
683 end = strlen(file_name);
684 while (end > 0 && file_name[end - 1] == '/') {
689 return all_slashes_name(file_name);
693 while (start > 0 && file_name[start - 1] != '/') {
697 return xmemdup0(file_name + start, end - start);
700 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
701 * returns an absolute path to 'file_name' considering it relative to 'dir',
702 * which itself must be absolute. 'dir' may be null or the empty string, in
703 * which case the current working directory is used.
705 * Returns a null pointer if 'dir' is null and getcwd() fails. */
707 abs_file_name(const char *dir, const char *file_name)
709 if (file_name[0] == '/') {
710 return xstrdup(file_name);
711 } else if (dir && dir[0]) {
712 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
713 return xasprintf("%s%s%s", dir, separator, file_name);
715 char *cwd = get_cwd();
717 char *abs_name = xasprintf("%s/%s", cwd, file_name);
726 /* Like readlink(), but returns the link name as a null-terminated string in
727 * allocated memory that the caller must eventually free (with free()).
728 * Returns NULL on error, in which case errno is set appropriately. */
730 xreadlink(const char *filename)
734 for (size = 64; ; size *= 2) {
735 char *buf = xmalloc(size);
736 ssize_t retval = readlink(filename, buf, size);
739 if (retval >= 0 && retval < size) {
752 /* Returns a version of 'filename' with symlinks in the final component
753 * dereferenced. This differs from realpath() in that:
755 * - 'filename' need not exist.
757 * - If 'filename' does exist as a symlink, its referent need not exist.
759 * - Only symlinks in the final component of 'filename' are dereferenced.
761 * The caller must eventually free the returned string (with free()). */
763 follow_symlinks(const char *filename)
769 fn = xstrdup(filename);
770 for (i = 0; i < 10; i++) {
774 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
778 linkname = xreadlink(fn);
780 VLOG_WARN("%s: readlink failed (%s)",
781 filename, ovs_strerror(errno));
785 if (linkname[0] == '/') {
786 /* Target of symlink is absolute so use it raw. */
789 /* Target of symlink is relative so add to 'fn''s directory. */
790 char *dir = dir_name(fn);
792 if (!strcmp(dir, ".")) {
795 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
796 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
807 VLOG_WARN("%s: too many levels of symlinks", filename);
809 return xstrdup(filename);
812 /* Pass a value to this function if it is marked with
813 * __attribute__((warn_unused_result)) and you genuinely want to ignore
814 * its return value. (Note that every scalar type can be implicitly
815 * converted to bool.) */
816 void ignore(bool x OVS_UNUSED) { }
818 /* Returns an appropriate delimiter for inserting just before the 0-based item
819 * 'index' in a list that has 'total' items in it. */
821 english_list_delimiter(size_t index, size_t total)
823 return (index == 0 ? ""
824 : index < total - 1 ? ", "
825 : total > 2 ? ", and "
829 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
830 * to finding the bit position of the most significant one bit in 'n'. It is
831 * an error to call this function with 'n' == 0. */
833 log_2_floor(uint32_t n)
837 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
838 #error "Someone screwed up the #includes."
839 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
840 return 31 - __builtin_clz(n);
845 #define BIN_SEARCH_STEP(BITS) \
846 if (n >= (1 << BITS)) { \
855 #undef BIN_SEARCH_STEP
861 /* Given a 32 bit word 'n', calculates ceil(log_2('n')). It is an error to
862 * call this function with 'n' == 0. */
864 log_2_ceil(uint32_t n)
866 return log_2_floor(n) + !is_pow2(n);
869 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
870 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
871 #error "Someone screwed up the #includes."
872 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
873 /* Defined inline in util.h. */
881 #define CTZ_STEP(X) \
898 /* Returns the number of 1-bits in 'x', between 0 and 32 inclusive. */
902 /* In my testing, this implementation is over twice as fast as any other
903 * portable implementation that I tried, including GCC 4.4
904 * __builtin_popcount(), although nonportable asm("popcnt") was over 50%
907 ((((X) & (1 << 0)) != 0) + \
908 (((X) & (1 << 1)) != 0) + \
909 (((X) & (1 << 2)) != 0) + \
910 (((X) & (1 << 3)) != 0) + \
911 (((X) & (1 << 4)) != 0) + \
912 (((X) & (1 << 5)) != 0) + \
913 (((X) & (1 << 6)) != 0) + \
914 (((X) & (1 << 7)) != 0))
915 #define INIT2(X) INIT1(X), INIT1((X) + 1)
916 #define INIT4(X) INIT2(X), INIT2((X) + 2)
917 #define INIT8(X) INIT4(X), INIT4((X) + 4)
918 #define INIT16(X) INIT8(X), INIT8((X) + 8)
919 #define INIT32(X) INIT16(X), INIT16((X) + 16)
920 #define INIT64(X) INIT32(X), INIT32((X) + 32)
922 static const uint8_t popcount8[256] = {
923 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
926 return (popcount8[x & 0xff] +
927 popcount8[(x >> 8) & 0xff] +
928 popcount8[(x >> 16) & 0xff] +
932 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
934 is_all_zeros(const uint8_t *p, size_t n)
938 for (i = 0; i < n; i++) {
946 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
948 is_all_ones(const uint8_t *p, size_t n)
952 for (i = 0; i < n; i++) {
960 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
961 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
962 * 'dst' is 'dst_len' bytes long.
964 * If you consider all of 'src' to be a single unsigned integer in network byte
965 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
966 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
967 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
968 * 2], and so on. Similarly for 'dst'.
970 * Required invariants:
971 * src_ofs + n_bits <= src_len * 8
972 * dst_ofs + n_bits <= dst_len * 8
973 * 'src' and 'dst' must not overlap.
976 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
977 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
980 const uint8_t *src = src_;
983 src += src_len - (src_ofs / 8 + 1);
986 dst += dst_len - (dst_ofs / 8 + 1);
989 if (src_ofs == 0 && dst_ofs == 0) {
990 unsigned int n_bytes = n_bits / 8;
994 memcpy(dst, src, n_bytes);
1001 uint8_t mask = (1 << n_bits) - 1;
1002 *dst = (*dst & ~mask) | (*src & mask);
1005 while (n_bits > 0) {
1006 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1007 unsigned int chunk = MIN(n_bits, max_copy);
1008 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1011 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1028 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1029 * 'dst_len' bytes long.
1031 * If you consider all of 'dst' to be a single unsigned integer in network byte
1032 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1033 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1034 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1037 * Required invariant:
1038 * dst_ofs + n_bits <= dst_len * 8
1041 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1042 unsigned int n_bits)
1044 uint8_t *dst = dst_;
1050 dst += dst_len - (dst_ofs / 8 + 1);
1054 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1056 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1066 while (n_bits >= 8) {
1072 *dst &= ~((1 << n_bits) - 1);
1076 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1077 * 'dst' is 'dst_len' bytes long.
1079 * If you consider all of 'dst' to be a single unsigned integer in network byte
1080 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1081 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1082 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1085 * Required invariant:
1086 * dst_ofs + n_bits <= dst_len * 8
1089 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1090 unsigned int n_bits)
1092 uint8_t *dst = dst_;
1098 dst += dst_len - (dst_ofs / 8 + 1);
1102 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1104 *dst |= ((1 << chunk) - 1) << dst_ofs;
1114 while (n_bits >= 8) {
1120 *dst |= (1 << n_bits) - 1;
1124 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1125 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1128 * If you consider all of 'dst' to be a single unsigned integer in network byte
1129 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1130 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1131 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1134 * Required invariant:
1135 * dst_ofs + n_bits <= dst_len * 8
1138 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1139 unsigned int n_bits)
1141 const uint8_t *p = p_;
1147 p += len - (ofs / 8 + 1);
1151 unsigned int chunk = MIN(n_bits, 8 - ofs);
1153 if (*p & (((1 << chunk) - 1) << ofs)) {
1165 while (n_bits >= 8) {
1173 if (n_bits && *p & ((1 << n_bits) - 1)) {
1180 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1181 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1183 * If you consider all of 'dst' to be a single unsigned integer in network byte
1184 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1185 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1186 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1189 * Required invariants:
1190 * dst_ofs + n_bits <= dst_len * 8
1194 bitwise_put(uint64_t value,
1195 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1196 unsigned int n_bits)
1198 ovs_be64 n_value = htonll(value);
1199 bitwise_copy(&n_value, sizeof n_value, 0,
1200 dst, dst_len, dst_ofs,
1204 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1205 * which is 'src_len' bytes long.
1207 * If you consider all of 'src' to be a single unsigned integer in network byte
1208 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1209 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1210 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1213 * Required invariants:
1214 * src_ofs + n_bits <= src_len * 8
1218 bitwise_get(const void *src, unsigned int src_len,
1219 unsigned int src_ofs, unsigned int n_bits)
1221 ovs_be64 value = htonll(0);
1223 bitwise_copy(src, src_len, src_ofs,
1224 &value, sizeof value, 0,
1226 return ntohll(value);