1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * tools/testing/selftests/kvm/lib/test_util.c
4 *
5 * Copyright (C) 2020, Google LLC.
6 */
7
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <assert.h>
12 #include <ctype.h>
13 #include <limits.h>
14 #include <stdlib.h>
15 #include <time.h>
16 #include <sys/stat.h>
17 #include <sys/syscall.h>
18 #include <linux/mman.h>
19 #include "linux/kernel.h"
20
21 #include "test_util.h"
22
23 /*
24 * Random number generator that is usable from guest code. This is the
25 * Park-Miller LCG using standard constants.
26 */
27
new_guest_random_state(uint32_t seed)28 struct guest_random_state new_guest_random_state(uint32_t seed)
29 {
30 struct guest_random_state s = {.seed = seed};
31 return s;
32 }
33
guest_random_u32(struct guest_random_state * state)34 uint32_t guest_random_u32(struct guest_random_state *state)
35 {
36 state->seed = (uint64_t)state->seed * 48271 % ((uint32_t)(1 << 31) - 1);
37 return state->seed;
38 }
39
40 /*
41 * Parses "[0-9]+[kmgt]?".
42 */
parse_size(const char * size)43 size_t parse_size(const char *size)
44 {
45 size_t base;
46 char *scale;
47 int shift = 0;
48
49 TEST_ASSERT(size && isdigit(size[0]), "Need at least one digit in '%s'", size);
50
51 base = strtoull(size, &scale, 0);
52
53 TEST_ASSERT(base != ULLONG_MAX, "Overflow parsing size!");
54
55 switch (tolower(*scale)) {
56 case 't':
57 shift = 40;
58 break;
59 case 'g':
60 shift = 30;
61 break;
62 case 'm':
63 shift = 20;
64 break;
65 case 'k':
66 shift = 10;
67 break;
68 case 'b':
69 case '\0':
70 shift = 0;
71 break;
72 default:
73 TEST_ASSERT(false, "Unknown size letter %c", *scale);
74 }
75
76 TEST_ASSERT((base << shift) >> shift == base, "Overflow scaling size!");
77
78 return base << shift;
79 }
80
timespec_to_ns(struct timespec ts)81 int64_t timespec_to_ns(struct timespec ts)
82 {
83 return (int64_t)ts.tv_nsec + 1000000000LL * (int64_t)ts.tv_sec;
84 }
85
timespec_add_ns(struct timespec ts,int64_t ns)86 struct timespec timespec_add_ns(struct timespec ts, int64_t ns)
87 {
88 struct timespec res;
89
90 res.tv_nsec = ts.tv_nsec + ns;
91 res.tv_sec = ts.tv_sec + res.tv_nsec / 1000000000LL;
92 res.tv_nsec %= 1000000000LL;
93
94 return res;
95 }
96
timespec_add(struct timespec ts1,struct timespec ts2)97 struct timespec timespec_add(struct timespec ts1, struct timespec ts2)
98 {
99 int64_t ns1 = timespec_to_ns(ts1);
100 int64_t ns2 = timespec_to_ns(ts2);
101 return timespec_add_ns((struct timespec){0}, ns1 + ns2);
102 }
103
timespec_sub(struct timespec ts1,struct timespec ts2)104 struct timespec timespec_sub(struct timespec ts1, struct timespec ts2)
105 {
106 int64_t ns1 = timespec_to_ns(ts1);
107 int64_t ns2 = timespec_to_ns(ts2);
108 return timespec_add_ns((struct timespec){0}, ns1 - ns2);
109 }
110
timespec_elapsed(struct timespec start)111 struct timespec timespec_elapsed(struct timespec start)
112 {
113 struct timespec end;
114
115 clock_gettime(CLOCK_MONOTONIC, &end);
116 return timespec_sub(end, start);
117 }
118
timespec_div(struct timespec ts,int divisor)119 struct timespec timespec_div(struct timespec ts, int divisor)
120 {
121 int64_t ns = timespec_to_ns(ts) / divisor;
122
123 return timespec_add_ns((struct timespec){0}, ns);
124 }
125
print_skip(const char * fmt,...)126 void print_skip(const char *fmt, ...)
127 {
128 va_list ap;
129
130 assert(fmt);
131 va_start(ap, fmt);
132 vprintf(fmt, ap);
133 va_end(ap);
134 puts(", skipping test");
135 }
136
thp_configured(void)137 bool thp_configured(void)
138 {
139 int ret;
140 struct stat statbuf;
141
142 ret = stat("/sys/kernel/mm/transparent_hugepage", &statbuf);
143 TEST_ASSERT(ret == 0 || (ret == -1 && errno == ENOENT),
144 "Error in stating /sys/kernel/mm/transparent_hugepage");
145
146 return ret == 0;
147 }
148
get_trans_hugepagesz(void)149 size_t get_trans_hugepagesz(void)
150 {
151 size_t size;
152 FILE *f;
153 int ret;
154
155 TEST_ASSERT(thp_configured(), "THP is not configured in host kernel");
156
157 f = fopen("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size", "r");
158 TEST_ASSERT(f != NULL, "Error in opening transparent_hugepage/hpage_pmd_size");
159
160 ret = fscanf(f, "%ld", &size);
161 ret = fscanf(f, "%ld", &size);
162 TEST_ASSERT(ret < 1, "Error reading transparent_hugepage/hpage_pmd_size");
163 fclose(f);
164
165 return size;
166 }
167
get_def_hugetlb_pagesz(void)168 size_t get_def_hugetlb_pagesz(void)
169 {
170 char buf[64];
171 const char *hugepagesize = "Hugepagesize:";
172 const char *hugepages_total = "HugePages_Total:";
173 FILE *f;
174
175 f = fopen("/proc/meminfo", "r");
176 TEST_ASSERT(f != NULL, "Error in opening /proc/meminfo");
177
178 while (fgets(buf, sizeof(buf), f) != NULL) {
179 if (strstr(buf, hugepages_total) == buf) {
180 unsigned long long total = strtoull(buf + strlen(hugepages_total), NULL, 10);
181 if (!total) {
182 fprintf(stderr, "HUGETLB is not enabled in /proc/sys/vm/nr_hugepages\n");
183 exit(KSFT_SKIP);
184 }
185 }
186 if (strstr(buf, hugepagesize) == buf) {
187 fclose(f);
188 return strtoull(buf + strlen(hugepagesize), NULL, 10) << 10;
189 }
190 }
191
192 if (feof(f)) {
193 fprintf(stderr, "HUGETLB is not configured in host kernel");
194 exit(KSFT_SKIP);
195 }
196
197 TEST_FAIL("Error in reading /proc/meminfo");
198 }
199
200 #define ANON_FLAGS (MAP_PRIVATE | MAP_ANONYMOUS)
201 #define ANON_HUGE_FLAGS (ANON_FLAGS | MAP_HUGETLB)
202
vm_mem_backing_src_alias(uint32_t i)203 const struct vm_mem_backing_src_alias *vm_mem_backing_src_alias(uint32_t i)
204 {
205 static const struct vm_mem_backing_src_alias aliases[] = {
206 [VM_MEM_SRC_ANONYMOUS] = {
207 .name = "anonymous",
208 .flag = ANON_FLAGS,
209 },
210 [VM_MEM_SRC_ANONYMOUS_THP] = {
211 .name = "anonymous_thp",
212 .flag = ANON_FLAGS,
213 },
214 [VM_MEM_SRC_ANONYMOUS_HUGETLB] = {
215 .name = "anonymous_hugetlb",
216 .flag = ANON_HUGE_FLAGS,
217 },
218 [VM_MEM_SRC_ANONYMOUS_HUGETLB_16KB] = {
219 .name = "anonymous_hugetlb_16kb",
220 .flag = ANON_HUGE_FLAGS | MAP_HUGE_16KB,
221 },
222 [VM_MEM_SRC_ANONYMOUS_HUGETLB_64KB] = {
223 .name = "anonymous_hugetlb_64kb",
224 .flag = ANON_HUGE_FLAGS | MAP_HUGE_64KB,
225 },
226 [VM_MEM_SRC_ANONYMOUS_HUGETLB_512KB] = {
227 .name = "anonymous_hugetlb_512kb",
228 .flag = ANON_HUGE_FLAGS | MAP_HUGE_512KB,
229 },
230 [VM_MEM_SRC_ANONYMOUS_HUGETLB_1MB] = {
231 .name = "anonymous_hugetlb_1mb",
232 .flag = ANON_HUGE_FLAGS | MAP_HUGE_1MB,
233 },
234 [VM_MEM_SRC_ANONYMOUS_HUGETLB_2MB] = {
235 .name = "anonymous_hugetlb_2mb",
236 .flag = ANON_HUGE_FLAGS | MAP_HUGE_2MB,
237 },
238 [VM_MEM_SRC_ANONYMOUS_HUGETLB_8MB] = {
239 .name = "anonymous_hugetlb_8mb",
240 .flag = ANON_HUGE_FLAGS | MAP_HUGE_8MB,
241 },
242 [VM_MEM_SRC_ANONYMOUS_HUGETLB_16MB] = {
243 .name = "anonymous_hugetlb_16mb",
244 .flag = ANON_HUGE_FLAGS | MAP_HUGE_16MB,
245 },
246 [VM_MEM_SRC_ANONYMOUS_HUGETLB_32MB] = {
247 .name = "anonymous_hugetlb_32mb",
248 .flag = ANON_HUGE_FLAGS | MAP_HUGE_32MB,
249 },
250 [VM_MEM_SRC_ANONYMOUS_HUGETLB_256MB] = {
251 .name = "anonymous_hugetlb_256mb",
252 .flag = ANON_HUGE_FLAGS | MAP_HUGE_256MB,
253 },
254 [VM_MEM_SRC_ANONYMOUS_HUGETLB_512MB] = {
255 .name = "anonymous_hugetlb_512mb",
256 .flag = ANON_HUGE_FLAGS | MAP_HUGE_512MB,
257 },
258 [VM_MEM_SRC_ANONYMOUS_HUGETLB_1GB] = {
259 .name = "anonymous_hugetlb_1gb",
260 .flag = ANON_HUGE_FLAGS | MAP_HUGE_1GB,
261 },
262 [VM_MEM_SRC_ANONYMOUS_HUGETLB_2GB] = {
263 .name = "anonymous_hugetlb_2gb",
264 .flag = ANON_HUGE_FLAGS | MAP_HUGE_2GB,
265 },
266 [VM_MEM_SRC_ANONYMOUS_HUGETLB_16GB] = {
267 .name = "anonymous_hugetlb_16gb",
268 .flag = ANON_HUGE_FLAGS | MAP_HUGE_16GB,
269 },
270 [VM_MEM_SRC_SHMEM] = {
271 .name = "shmem",
272 .flag = MAP_SHARED,
273 },
274 [VM_MEM_SRC_SHARED_HUGETLB] = {
275 .name = "shared_hugetlb",
276 /*
277 * No MAP_HUGETLB, we use MFD_HUGETLB instead. Since
278 * we're using "file backed" memory, we need to specify
279 * this when the FD is created, not when the area is
280 * mapped.
281 */
282 .flag = MAP_SHARED,
283 },
284 };
285 _Static_assert(ARRAY_SIZE(aliases) == NUM_SRC_TYPES,
286 "Missing new backing src types?");
287
288 TEST_ASSERT(i < NUM_SRC_TYPES, "Backing src type ID %d too big", i);
289
290 return &aliases[i];
291 }
292
293 #define MAP_HUGE_PAGE_SIZE(x) (1ULL << ((x >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK))
294
get_backing_src_pagesz(uint32_t i)295 size_t get_backing_src_pagesz(uint32_t i)
296 {
297 uint32_t flag = vm_mem_backing_src_alias(i)->flag;
298
299 switch (i) {
300 case VM_MEM_SRC_ANONYMOUS:
301 case VM_MEM_SRC_SHMEM:
302 return getpagesize();
303 case VM_MEM_SRC_ANONYMOUS_THP:
304 return get_trans_hugepagesz();
305 case VM_MEM_SRC_ANONYMOUS_HUGETLB:
306 case VM_MEM_SRC_SHARED_HUGETLB:
307 return get_def_hugetlb_pagesz();
308 default:
309 return MAP_HUGE_PAGE_SIZE(flag);
310 }
311 }
312
is_backing_src_hugetlb(uint32_t i)313 bool is_backing_src_hugetlb(uint32_t i)
314 {
315 return !!(vm_mem_backing_src_alias(i)->flag & MAP_HUGETLB);
316 }
317
print_available_backing_src_types(const char * prefix)318 static void print_available_backing_src_types(const char *prefix)
319 {
320 int i;
321
322 printf("%sAvailable backing src types:\n", prefix);
323
324 for (i = 0; i < NUM_SRC_TYPES; i++)
325 printf("%s %s\n", prefix, vm_mem_backing_src_alias(i)->name);
326 }
327
backing_src_help(const char * flag)328 void backing_src_help(const char *flag)
329 {
330 printf(" %s: specify the type of memory that should be used to\n"
331 " back the guest data region. (default: %s)\n",
332 flag, vm_mem_backing_src_alias(DEFAULT_VM_MEM_SRC)->name);
333 print_available_backing_src_types(" ");
334 }
335
parse_backing_src_type(const char * type_name)336 enum vm_mem_backing_src_type parse_backing_src_type(const char *type_name)
337 {
338 int i;
339
340 for (i = 0; i < NUM_SRC_TYPES; i++)
341 if (!strcmp(type_name, vm_mem_backing_src_alias(i)->name))
342 return i;
343
344 print_available_backing_src_types("");
345 TEST_FAIL("Unknown backing src type: %s", type_name);
346 return -1;
347 }
348
get_run_delay(void)349 long get_run_delay(void)
350 {
351 char path[64];
352 long val[2];
353 FILE *fp;
354
355 sprintf(path, "/proc/%ld/schedstat", syscall(SYS_gettid));
356 fp = fopen(path, "r");
357 /* Return MIN_RUN_DELAY_NS upon failure just to be safe */
358 if (fscanf(fp, "%ld %ld ", &val[0], &val[1]) < 2)
359 val[1] = MIN_RUN_DELAY_NS;
360 fclose(fp);
361
362 return val[1];
363 }
364
atoi_paranoid(const char * num_str)365 int atoi_paranoid(const char *num_str)
366 {
367 char *end_ptr;
368 long num;
369
370 errno = 0;
371 num = strtol(num_str, &end_ptr, 0);
372 TEST_ASSERT(!errno, "strtol(\"%s\") failed", num_str);
373 TEST_ASSERT(num_str != end_ptr,
374 "strtol(\"%s\") didn't find a valid integer.", num_str);
375 TEST_ASSERT(*end_ptr == '\0',
376 "strtol(\"%s\") failed to parse trailing characters \"%s\".",
377 num_str, end_ptr);
378 TEST_ASSERT(num >= INT_MIN && num <= INT_MAX,
379 "%ld not in range of [%d, %d]", num, INT_MIN, INT_MAX);
380
381 return num;
382 }
383
strdup_printf(const char * fmt,...)384 char *strdup_printf(const char *fmt, ...)
385 {
386 va_list ap;
387 char *str;
388
389 va_start(ap, fmt);
390 TEST_ASSERT(vasprintf(&str, fmt, ap) >= 0, "vasprintf() failed");
391 va_end(ap);
392
393 return str;
394 }
395