1 // SPDX-License-Identifier: GPL-2.0-only
3 * tools/testing/selftests/kvm/lib/test_util.c
5 * Copyright (C) 2020, Google LLC.
13 #include "linux/kernel.h"
15 #include "test_util.h"
18 * Parses "[0-9]+[kmgt]?".
20 size_t parse_size(const char *size)
26 TEST_ASSERT(size && isdigit(size[0]), "Need at least one digit in '%s'", size);
28 base = strtoull(size, &scale, 0);
30 TEST_ASSERT(base != ULLONG_MAX, "Overflow parsing size!");
32 switch (tolower(*scale)) {
50 TEST_ASSERT(false, "Unknown size letter %c", *scale);
53 TEST_ASSERT((base << shift) >> shift == base, "Overflow scaling size!");
58 int64_t timespec_to_ns(struct timespec ts)
60 return (int64_t)ts.tv_nsec + 1000000000LL * (int64_t)ts.tv_sec;
63 struct timespec timespec_add_ns(struct timespec ts, int64_t ns)
67 res.tv_nsec = ts.tv_nsec + ns;
68 res.tv_sec = ts.tv_sec + res.tv_nsec / 1000000000LL;
69 res.tv_nsec %= 1000000000LL;
74 struct timespec timespec_add(struct timespec ts1, struct timespec ts2)
76 int64_t ns1 = timespec_to_ns(ts1);
77 int64_t ns2 = timespec_to_ns(ts2);
78 return timespec_add_ns((struct timespec){0}, ns1 + ns2);
81 struct timespec timespec_sub(struct timespec ts1, struct timespec ts2)
83 int64_t ns1 = timespec_to_ns(ts1);
84 int64_t ns2 = timespec_to_ns(ts2);
85 return timespec_add_ns((struct timespec){0}, ns1 - ns2);
88 struct timespec timespec_elapsed(struct timespec start)
92 clock_gettime(CLOCK_MONOTONIC, &end);
93 return timespec_sub(end, start);
96 struct timespec timespec_div(struct timespec ts, int divisor)
98 int64_t ns = timespec_to_ns(ts) / divisor;
100 return timespec_add_ns((struct timespec){0}, ns);
103 void print_skip(const char *fmt, ...)
111 puts(", skipping test");
114 const struct vm_mem_backing_src_alias backing_src_aliases[] = {
115 {"anonymous", VM_MEM_SRC_ANONYMOUS,},
116 {"anonymous_thp", VM_MEM_SRC_ANONYMOUS_THP,},
117 {"anonymous_hugetlb", VM_MEM_SRC_ANONYMOUS_HUGETLB,},
120 void backing_src_help(void)
124 printf("Available backing src types:\n");
125 for (i = 0; i < ARRAY_SIZE(backing_src_aliases); i++)
126 printf("\t%s\n", backing_src_aliases[i].name);
129 enum vm_mem_backing_src_type parse_backing_src_type(const char *type_name)
133 for (i = 0; i < ARRAY_SIZE(backing_src_aliases); i++)
134 if (!strcmp(type_name, backing_src_aliases[i].name))
135 return backing_src_aliases[i].type;
138 TEST_FAIL("Unknown backing src type: %s", type_name);