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