2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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.
31 #include "byte-order.h"
34 #include "ovs-thread.h"
36 #ifdef HAVE_PTHREAD_SET_NAME_NP
37 #include <pthread_np.h>
40 VLOG_DEFINE_THIS_MODULE(util);
42 COVERAGE_DEFINE(util_xalloc);
44 /* argv[0] without directory names. */
45 const char *program_name;
47 /* Name for the currently running thread or process, for log messages, process
48 * listings, and debuggers. */
49 DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name);
51 /* --version option output. */
52 static char *program_version;
54 /* Buffer used by ovs_strerror() and ovs_format_message(). */
55 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
59 static char *xreadlink(const char *filename);
62 ovs_assert_failure(const char *where, const char *function,
63 const char *condition)
65 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
66 * to trigger an assertion failure of its own. */
67 static int reentry = 0;
71 VLOG_ABORT("%s: assertion %s failed in %s()",
72 where, condition, function);
76 fprintf(stderr, "%s: assertion %s failed in %s()",
77 where, condition, function);
88 ovs_abort(0, "virtual memory exhausted");
92 xcalloc(size_t count, size_t size)
94 void *p = count && size ? calloc(count, size) : malloc(1);
95 COVERAGE_INC(util_xalloc);
105 return xcalloc(1, size);
111 void *p = malloc(size ? size : 1);
112 COVERAGE_INC(util_xalloc);
120 xrealloc(void *p, size_t size)
122 p = realloc(p, size ? size : 1);
123 COVERAGE_INC(util_xalloc);
131 xmemdup(const void *p_, size_t size)
133 void *p = xmalloc(size);
139 xmemdup0(const char *p_, size_t length)
141 char *p = xmalloc(length + 1);
142 memcpy(p, p_, length);
148 xstrdup(const char *s)
150 return xmemdup0(s, strlen(s));
154 xvasprintf(const char *format, va_list args)
160 va_copy(args2, args);
161 needed = vsnprintf(NULL, 0, format, args);
163 s = xmalloc(needed + 1);
165 vsnprintf(s, needed + 1, format, args2);
172 x2nrealloc(void *p, size_t *n, size_t s)
174 *n = *n == 0 ? 1 : 2 * *n;
175 return xrealloc(p, *n * s);
178 /* The desired minimum alignment for an allocated block of memory. */
179 #define MEM_ALIGN MAX(sizeof(void *), 8)
180 BUILD_ASSERT_DECL(IS_POW2(MEM_ALIGN));
181 BUILD_ASSERT_DECL(CACHE_LINE_SIZE >= MEM_ALIGN);
183 /* Allocates and returns 'size' bytes of memory in dedicated cache lines. That
184 * is, the memory block returned will not share a cache line with other data,
185 * avoiding "false sharing". (The memory returned will not be at the start of
186 * a cache line, though, so don't assume such alignment.)
188 * Use free_cacheline() to free the returned memory block. */
190 xmalloc_cacheline(size_t size)
195 /* Allocate room for:
197 * - Up to CACHE_LINE_SIZE - 1 bytes before the payload, so that the
198 * start of the payload doesn't potentially share a cache line.
200 * - A payload consisting of a void *, followed by padding out to
201 * MEM_ALIGN bytes, followed by 'size' bytes of user data.
203 * - Space following the payload up to the end of the cache line, so
204 * that the end of the payload doesn't potentially share a cache line
205 * with some following block. */
206 base = xmalloc((CACHE_LINE_SIZE - 1)
207 + ROUND_UP(MEM_ALIGN + size, CACHE_LINE_SIZE));
209 /* Locate the payload and store a pointer to the base at the beginning. */
210 payload = (void **) ROUND_UP((uintptr_t) base, CACHE_LINE_SIZE);
213 return (char *) payload + MEM_ALIGN;
216 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
219 xzalloc_cacheline(size_t size)
221 void *p = xmalloc_cacheline(size);
226 /* Frees a memory block allocated with xmalloc_cacheline() or
227 * xzalloc_cacheline(). */
229 free_cacheline(void *p)
232 free(*(void **) ((uintptr_t) p - MEM_ALIGN));
237 xasprintf(const char *format, ...)
242 va_start(args, format);
243 s = xvasprintf(format, args);
249 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
250 * bytes from 'src' and doesn't return anything. */
252 ovs_strlcpy(char *dst, const char *src, size_t size)
255 size_t len = strnlen(src, size - 1);
256 memcpy(dst, src, len);
261 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
262 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
263 * to every otherwise unused byte in 'dst'.
265 * Except for performance, the following call:
266 * ovs_strzcpy(dst, src, size);
267 * is equivalent to these two calls:
268 * memset(dst, '\0', size);
269 * ovs_strlcpy(dst, src, size);
271 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
274 ovs_strzcpy(char *dst, const char *src, size_t size)
277 size_t len = strnlen(src, size - 1);
278 memcpy(dst, src, len);
279 memset(dst + len, '\0', size - len);
283 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
284 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
285 * the message inside parentheses. Then, terminates with abort().
287 * This function is preferred to ovs_fatal() in a situation where it would make
288 * sense for a monitoring process to restart the daemon.
290 * 'format' should not end with a new-line, because this function will add one
293 ovs_abort(int err_no, const char *format, ...)
297 va_start(args, format);
298 ovs_abort_valist(err_no, format, args);
301 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
303 ovs_abort_valist(int err_no, const char *format, va_list args)
305 ovs_error_valist(err_no, format, args);
309 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
310 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
311 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
313 * 'format' should not end with a new-line, because this function will add one
316 ovs_fatal(int err_no, const char *format, ...)
320 va_start(args, format);
321 ovs_fatal_valist(err_no, format, args);
324 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
326 ovs_fatal_valist(int err_no, const char *format, va_list args)
328 ovs_error_valist(err_no, format, args);
332 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
333 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
334 * the message inside parentheses.
336 * 'format' should not end with a new-line, because this function will add one
339 ovs_error(int err_no, const char *format, ...)
343 va_start(args, format);
344 ovs_error_valist(err_no, format, args);
348 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
350 ovs_error_valist(int err_no, const char *format, va_list args)
352 const char *subprogram_name = get_subprogram_name();
353 int save_errno = errno;
355 if (subprogram_name[0]) {
356 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
358 fprintf(stderr, "%s: ", program_name);
361 vfprintf(stderr, format, args);
363 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
370 /* Many OVS functions return an int which is one of:
373 * - EOF: end of file (not necessarily an error; depends on the function called)
375 * Returns the appropriate human-readable string. The caller must copy the
376 * string if it wants to hold onto it, as the storage may be overwritten on
377 * subsequent function calls.
380 ovs_retval_to_string(int retval)
383 : retval == EOF ? "End of file"
384 : ovs_strerror(retval));
387 /* This function returns the string describing the error number in 'error'
388 * for POSIX platforms. For Windows, this function can be used for C library
389 * calls. For socket calls that are also used in Windows, use sock_strerror()
390 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
392 ovs_strerror(int error)
394 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
400 buffer = strerror_buffer_get()->s;
402 #if STRERROR_R_CHAR_P
403 /* GNU style strerror_r() might return an immutable static string, or it
404 * might write and return 'buffer', but in either case we can pass the
405 * returned string directly to the caller. */
406 s = strerror_r(error, buffer, BUFSIZE);
407 #else /* strerror_r() returns an int. */
409 if (strerror_r(error, buffer, BUFSIZE)) {
410 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
411 * is too short). We don't check the actual failure reason because
412 * POSIX requires strerror_r() to return the error but old glibc
413 * (before 2.13) returns -1 and sets errno. */
414 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
423 /* Sets global "program_name" and "program_version" variables. Should
424 * be called at the beginning of main() with "argv[0]" as the argument
427 * 'version' should contain the version of the caller's program. If 'version'
428 * is the same as the VERSION #define, the caller is assumed to be part of Open
429 * vSwitch. Otherwise, it is assumed to be an external program linking against
430 * the Open vSwitch libraries.
432 * The 'date' and 'time' arguments should likely be called with
433 * "__DATE__" and "__TIME__" to use the time the binary was built.
434 * Alternatively, the "set_program_name" macro may be called to do this
438 set_program_name__(const char *argv0, const char *version, const char *date,
443 size_t max_len = strlen(argv0) + 1;
448 basename = xmalloc(max_len);
449 _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
450 assert_single_threaded();
451 program_name = basename;
453 const char *slash = strrchr(argv0, '/');
454 assert_single_threaded();
455 program_name = slash ? slash + 1 : argv0;
458 free(program_version);
460 if (!strcmp(version, VERSION)) {
461 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
463 program_name, date, time);
465 program_version = xasprintf("%s %s\n"
466 "Open vSwitch Library "VERSION"\n"
468 program_name, version, date, time);
472 /* Returns the name of the currently running thread or process. */
474 get_subprogram_name(void)
476 const char *name = subprogram_name_get();
477 return name ? name : "";
480 /* Sets the formatted value of 'format' as the name of the currently running
481 * thread or process. (This appears in log messages and may also be visible in
482 * system process listings and debuggers.) */
484 set_subprogram_name(const char *format, ...)
491 va_start(args, format);
492 pname = xvasprintf(format, args);
495 pname = xstrdup(program_name);
498 free(subprogram_name_set(pname));
500 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
501 pthread_setname_np(pthread_self(), pname);
502 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
503 pthread_setname_np(pthread_self(), "%s", pname);
504 #elif HAVE_PTHREAD_SET_NAME_NP
505 pthread_set_name_np(pthread_self(), pname);
509 /* Returns a pointer to a string describing the program version. The
510 * caller must not modify or free the returned string.
513 get_program_version(void)
515 return program_version;
518 /* Print the version information for the program. */
520 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
522 printf("%s", program_version);
523 if (min_ofp || max_ofp) {
524 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
528 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
529 * line. Numeric offsets are also included, starting at 'ofs' for the first
530 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
531 * are also rendered alongside. */
533 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
534 uintptr_t ofs, bool ascii)
536 const uint8_t *buf = buf_;
537 const size_t per_line = 16; /* Maximum bytes per line. */
541 size_t start, end, n;
544 /* Number of bytes on this line. */
545 start = ofs % per_line;
547 if (end - start > size)
552 fprintf(stream, "%08"PRIxMAX" ", (uintmax_t) ROUND_DOWN(ofs, per_line));
553 for (i = 0; i < start; i++)
554 fprintf(stream, " ");
556 fprintf(stream, "%02x%c",
557 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
560 for (; i < per_line; i++)
561 fprintf(stream, " ");
562 fprintf(stream, "|");
563 for (i = 0; i < start; i++)
564 fprintf(stream, " ");
565 for (; i < end; i++) {
566 int c = buf[i - start];
567 putc(c >= 32 && c < 127 ? c : '.', stream);
569 for (; i < per_line; i++)
570 fprintf(stream, " ");
571 fprintf(stream, "|");
573 fprintf(stream, "\n");
582 str_to_int(const char *s, int base, int *i)
585 bool ok = str_to_llong(s, base, &ll);
591 str_to_long(const char *s, int base, long *li)
594 bool ok = str_to_llong(s, base, &ll);
600 str_to_llong(const char *s, int base, long long *x)
602 int save_errno = errno;
605 *x = strtoll(s, &tail, base);
606 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
616 /* Converts floating-point string 's' into a double. If successful, stores
617 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
620 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
621 * (e.g. "1e9999)" is. */
623 str_to_double(const char *s, double *d)
625 int save_errno = errno;
628 *d = strtod(s, &tail);
629 if (errno == EINVAL || (errno == ERANGE && *d != 0)
630 || tail == s || *tail != '\0') {
640 /* Returns the value of 'c' as a hexadecimal digit. */
645 case '0': case '1': case '2': case '3': case '4':
646 case '5': case '6': case '7': case '8': case '9':
672 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
673 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
674 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
675 * non-hex digit is detected. */
677 hexits_value(const char *s, size_t n, bool *ok)
683 for (i = 0; i < n; i++) {
684 int hexit = hexit_value(s[i]);
691 value = (value << 4) + hexit;
699 /* Returns the current working directory as a malloc()'d string, or a null
700 * pointer if the current working directory cannot be determined. */
707 /* Get maximum path length or at least a reasonable estimate. */
709 path_max = pathconf(".", _PC_PATH_MAX);
713 size = (path_max < 0 ? 1024
714 : path_max > 10240 ? 10240
717 /* Get current working directory. */
719 char *buf = xmalloc(size);
720 if (getcwd(buf, size)) {
721 return xrealloc(buf, strlen(buf) + 1);
725 if (error != ERANGE) {
726 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
735 all_slashes_name(const char *s)
737 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
742 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
743 * similar to the POSIX dirname() function but thread-safe. */
745 dir_name(const char *file_name)
747 size_t len = strlen(file_name);
748 while (len > 0 && file_name[len - 1] == '/') {
751 while (len > 0 && file_name[len - 1] != '/') {
754 while (len > 0 && file_name[len - 1] == '/') {
757 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
760 /* Returns the file name portion of 'file_name' as a malloc()'d string,
761 * similar to the POSIX basename() function but thread-safe. */
763 base_name(const char *file_name)
767 end = strlen(file_name);
768 while (end > 0 && file_name[end - 1] == '/') {
773 return all_slashes_name(file_name);
777 while (start > 0 && file_name[start - 1] != '/') {
781 return xmemdup0(file_name + start, end - start);
784 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
785 * returns an absolute path to 'file_name' considering it relative to 'dir',
786 * which itself must be absolute. 'dir' may be null or the empty string, in
787 * which case the current working directory is used.
789 * Returns a null pointer if 'dir' is null and getcwd() fails. */
791 abs_file_name(const char *dir, const char *file_name)
793 if (file_name[0] == '/') {
794 return xstrdup(file_name);
795 } else if (dir && dir[0]) {
796 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
797 return xasprintf("%s%s%s", dir, separator, file_name);
799 char *cwd = get_cwd();
801 char *abs_name = xasprintf("%s/%s", cwd, file_name);
810 /* Like readlink(), but returns the link name as a null-terminated string in
811 * allocated memory that the caller must eventually free (with free()).
812 * Returns NULL on error, in which case errno is set appropriately. */
814 xreadlink(const char *filename)
818 for (size = 64; ; size *= 2) {
819 char *buf = xmalloc(size);
820 ssize_t retval = readlink(filename, buf, size);
823 if (retval >= 0 && retval < size) {
836 /* Returns a version of 'filename' with symlinks in the final component
837 * dereferenced. This differs from realpath() in that:
839 * - 'filename' need not exist.
841 * - If 'filename' does exist as a symlink, its referent need not exist.
843 * - Only symlinks in the final component of 'filename' are dereferenced.
845 * For Windows platform, this function returns a string that has the same
846 * value as the passed string.
848 * The caller must eventually free the returned string (with free()). */
850 follow_symlinks(const char *filename)
857 fn = xstrdup(filename);
858 for (i = 0; i < 10; i++) {
862 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
866 linkname = xreadlink(fn);
868 VLOG_WARN("%s: readlink failed (%s)",
869 filename, ovs_strerror(errno));
873 if (linkname[0] == '/') {
874 /* Target of symlink is absolute so use it raw. */
877 /* Target of symlink is relative so add to 'fn''s directory. */
878 char *dir = dir_name(fn);
880 if (!strcmp(dir, ".")) {
883 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
884 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
895 VLOG_WARN("%s: too many levels of symlinks", filename);
898 return xstrdup(filename);
901 /* Pass a value to this function if it is marked with
902 * __attribute__((warn_unused_result)) and you genuinely want to ignore
903 * its return value. (Note that every scalar type can be implicitly
904 * converted to bool.) */
905 void ignore(bool x OVS_UNUSED) { }
907 /* Returns an appropriate delimiter for inserting just before the 0-based item
908 * 'index' in a list that has 'total' items in it. */
910 english_list_delimiter(size_t index, size_t total)
912 return (index == 0 ? ""
913 : index < total - 1 ? ", "
914 : total > 2 ? ", and "
918 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
920 /* Defined inline in util.h. */
922 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
929 #define CTZ_STEP(X) \
946 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
948 raw_clz64(uint64_t n)
953 #define CLZ_STEP(X) \
971 #if NEED_COUNT_1BITS_8
973 ((((X) & (1 << 0)) != 0) + \
974 (((X) & (1 << 1)) != 0) + \
975 (((X) & (1 << 2)) != 0) + \
976 (((X) & (1 << 3)) != 0) + \
977 (((X) & (1 << 4)) != 0) + \
978 (((X) & (1 << 5)) != 0) + \
979 (((X) & (1 << 6)) != 0) + \
980 (((X) & (1 << 7)) != 0))
981 #define INIT2(X) INIT1(X), INIT1((X) + 1)
982 #define INIT4(X) INIT2(X), INIT2((X) + 2)
983 #define INIT8(X) INIT4(X), INIT4((X) + 4)
984 #define INIT16(X) INIT8(X), INIT8((X) + 8)
985 #define INIT32(X) INIT16(X), INIT16((X) + 16)
986 #define INIT64(X) INIT32(X), INIT32((X) + 32)
988 const uint8_t count_1bits_8[256] = {
989 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
993 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
995 is_all_zeros(const uint8_t *p, size_t n)
999 for (i = 0; i < n; i++) {
1007 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1009 is_all_ones(const uint8_t *p, size_t n)
1013 for (i = 0; i < n; i++) {
1021 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1022 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
1023 * 'dst' is 'dst_len' bytes long.
1025 * If you consider all of 'src' to be a single unsigned integer in network byte
1026 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1027 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1028 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1029 * 2], and so on. Similarly for 'dst'.
1031 * Required invariants:
1032 * src_ofs + n_bits <= src_len * 8
1033 * dst_ofs + n_bits <= dst_len * 8
1034 * 'src' and 'dst' must not overlap.
1037 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
1038 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
1039 unsigned int n_bits)
1041 const uint8_t *src = src_;
1042 uint8_t *dst = dst_;
1044 src += src_len - (src_ofs / 8 + 1);
1047 dst += dst_len - (dst_ofs / 8 + 1);
1050 if (src_ofs == 0 && dst_ofs == 0) {
1051 unsigned int n_bytes = n_bits / 8;
1055 memcpy(dst, src, n_bytes);
1062 uint8_t mask = (1 << n_bits) - 1;
1063 *dst = (*dst & ~mask) | (*src & mask);
1066 while (n_bits > 0) {
1067 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1068 unsigned int chunk = MIN(n_bits, max_copy);
1069 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1072 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1089 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1090 * 'dst_len' bytes long.
1092 * If you consider all of 'dst' to be a single unsigned integer in network byte
1093 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1094 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1095 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1098 * Required invariant:
1099 * dst_ofs + n_bits <= dst_len * 8
1102 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1103 unsigned int n_bits)
1105 uint8_t *dst = dst_;
1111 dst += dst_len - (dst_ofs / 8 + 1);
1115 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1117 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1127 while (n_bits >= 8) {
1133 *dst &= ~((1 << n_bits) - 1);
1137 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1138 * 'dst' is 'dst_len' bytes long.
1140 * If you consider all of 'dst' to be a single unsigned integer in network byte
1141 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1142 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1143 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1146 * Required invariant:
1147 * dst_ofs + n_bits <= dst_len * 8
1150 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1151 unsigned int n_bits)
1153 uint8_t *dst = dst_;
1159 dst += dst_len - (dst_ofs / 8 + 1);
1163 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1165 *dst |= ((1 << chunk) - 1) << dst_ofs;
1175 while (n_bits >= 8) {
1181 *dst |= (1 << n_bits) - 1;
1185 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1186 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1189 * If you consider all of 'dst' to be a single unsigned integer in network byte
1190 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1191 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1192 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1195 * Required invariant:
1196 * dst_ofs + n_bits <= dst_len * 8
1199 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1200 unsigned int n_bits)
1202 const uint8_t *p = p_;
1208 p += len - (ofs / 8 + 1);
1212 unsigned int chunk = MIN(n_bits, 8 - ofs);
1214 if (*p & (((1 << chunk) - 1) << ofs)) {
1226 while (n_bits >= 8) {
1234 if (n_bits && *p & ((1 << n_bits) - 1)) {
1241 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1242 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1244 * If you consider all of 'dst' to be a single unsigned integer in network byte
1245 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1246 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1247 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1250 * Required invariants:
1251 * dst_ofs + n_bits <= dst_len * 8
1255 bitwise_put(uint64_t value,
1256 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1257 unsigned int n_bits)
1259 ovs_be64 n_value = htonll(value);
1260 bitwise_copy(&n_value, sizeof n_value, 0,
1261 dst, dst_len, dst_ofs,
1265 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1266 * which is 'src_len' bytes long.
1268 * If you consider all of 'src' to be a single unsigned integer in network byte
1269 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1270 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1271 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1274 * Required invariants:
1275 * src_ofs + n_bits <= src_len * 8
1279 bitwise_get(const void *src, unsigned int src_len,
1280 unsigned int src_ofs, unsigned int n_bits)
1282 ovs_be64 value = htonll(0);
1284 bitwise_copy(src, src_len, src_ofs,
1285 &value, sizeof value, 0,
1287 return ntohll(value);
1308 skip_spaces(const char *s)
1310 while (isspace((unsigned char) *s)) {
1317 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1319 const char *start = s;
1324 negative = *s == '-';
1325 s += *s == '-' || *s == '+';
1327 if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1331 base = *s == '0' ? 8 : 10;
1334 if (s - start >= spec->width) {
1340 while (s - start < spec->width) {
1341 int digit = hexit_value(*s);
1343 if (digit < 0 || digit >= base) {
1346 value = value * base + digit;
1358 switch (spec->type) {
1362 *va_arg(*args, char *) = value;
1365 *va_arg(*args, short int *) = value;
1368 *va_arg(*args, int *) = value;
1371 *va_arg(*args, long int *) = value;
1374 *va_arg(*args, long long int *) = value;
1377 *va_arg(*args, intmax_t *) = value;
1379 case SCAN_PTRDIFF_T:
1380 *va_arg(*args, ptrdiff_t *) = value;
1383 *va_arg(*args, size_t *) = value;
1390 skip_digits(const char *s)
1392 while (*s >= '0' && *s <= '9') {
1399 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1401 const char *start = s;
1407 s += *s == '+' || *s == '-';
1410 s = skip_digits(s + 1);
1412 if (*s == 'e' || *s == 'E') {
1414 s += *s == '+' || *s == '-';
1418 if (s - start > spec->width) {
1419 s = start + spec->width;
1422 copy = xmemdup0(start, s - start);
1423 value = strtold(copy, &tail);
1430 switch (spec->type) {
1434 *va_arg(*args, float *) = value;
1437 *va_arg(*args, double *) = value;
1440 *va_arg(*args, long double *) = value;
1446 case SCAN_PTRDIFF_T:
1454 scan_output_string(const struct scan_spec *spec,
1455 const char *s, size_t n,
1458 if (spec->type != SCAN_DISCARD) {
1459 char *out = va_arg(*args, char *);
1466 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1470 for (n = 0; n < spec->width; n++) {
1471 if (!s[n] || isspace((unsigned char) s[n])) {
1479 scan_output_string(spec, s, n, args);
1484 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1486 const uint8_t *p = (const uint8_t *) p_;
1488 *complemented = *p == '^';
1492 bitmap_set1(set, ']');
1496 while (*p && *p != ']') {
1497 if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1498 bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1501 bitmap_set1(set, *p++);
1507 return (const char *) p;
1511 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1514 unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1518 /* Parse the scan set. */
1519 memset(set, 0, sizeof set);
1520 *pp = parse_scanset(*pp, set, &complemented);
1522 /* Parse the data. */
1525 && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1526 && n < spec->width) {
1532 scan_output_string(spec, s, n, args);
1537 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1539 unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1541 if (strlen(s) < n) {
1544 if (spec->type != SCAN_DISCARD) {
1545 memcpy(va_arg(*args, char *), s, n);
1550 /* This is an implementation of the standard sscanf() function, with the
1551 * following exceptions:
1553 * - It returns true if the entire format was successfully scanned and
1554 * converted, false if any conversion failed.
1556 * - The standard doesn't define sscanf() behavior when an out-of-range value
1557 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
1558 * implementations consider this an error and stop scanning. This
1559 * implementation never considers an out-of-range value an error; instead,
1560 * it stores the least-significant bits of the converted value in the
1561 * destination, e.g. the value 255 for both examples earlier.
1563 * - Only single-byte characters are supported, that is, the 'l' modifier
1564 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
1565 * also not supported.
1567 * - %p is not supported.
1570 ovs_scan(const char *s, const char *format, ...)
1572 const char *const start = s;
1577 va_start(args, format);
1579 while (*p != '\0') {
1580 struct scan_spec spec;
1581 unsigned char c = *p++;
1587 } else if (c != '%') {
1593 } else if (*p == '%') {
1601 /* Parse '*' flag. */
1602 discard = *p == '*';
1605 /* Parse field width. */
1607 while (*p >= '0' && *p <= '9') {
1608 spec.width = spec.width * 10 + (*p++ - '0');
1610 if (spec.width == 0) {
1611 spec.width = UINT_MAX;
1614 /* Parse type modifier. */
1618 spec.type = SCAN_CHAR;
1621 spec.type = SCAN_SHORT;
1627 spec.type = SCAN_INTMAX_T;
1633 spec.type = SCAN_LLONG;
1636 spec.type = SCAN_LONG;
1643 spec.type = SCAN_LLONG;
1648 spec.type = SCAN_PTRDIFF_T;
1653 spec.type = SCAN_SIZE_T;
1658 spec.type = SCAN_INT;
1663 spec.type = SCAN_DISCARD;
1667 if (c != 'c' && c != 'n' && c != '[') {
1672 s = scan_int(s, &spec, 10, &args);
1676 s = scan_int(s, &spec, 0, &args);
1680 s = scan_int(s, &spec, 8, &args);
1684 s = scan_int(s, &spec, 10, &args);
1689 s = scan_int(s, &spec, 16, &args);
1697 s = scan_float(s, &spec, &args);
1701 s = scan_string(s, &spec, &args);
1705 s = scan_set(s, &spec, &p, &args);
1709 s = scan_chars(s, &spec, &args);
1713 if (spec.type != SCAN_DISCARD) {
1714 *va_arg(args, int *) = s - start;
1731 xsleep(unsigned int seconds)
1733 ovsrcu_quiesce_start();
1735 Sleep(seconds * 1000);
1739 ovsrcu_quiesce_end();
1745 ovs_format_message(int error)
1747 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
1748 char *buffer = strerror_buffer_get()->s;
1750 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1751 NULL, error, 0, buffer, BUFSIZE, NULL);
1755 /* Returns a null-terminated string that explains the last error.
1756 * Use this function to get the error string for WINAPI calls. */
1758 ovs_lasterror_to_string(void)
1760 return ovs_format_message(GetLastError());
1764 ftruncate(int fd, off_t length)
1768 error = _chsize_s(fd, length);