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