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 *hugepagesize = "Hugepagesize:";
169 	const char *hugepages_total = "HugePages_Total:";
170 	FILE *f;
171 
172 	f = fopen("/proc/meminfo", "r");
173 	TEST_ASSERT(f != NULL, "Error in opening /proc/meminfo");
174 
175 	while (fgets(buf, sizeof(buf), f) != NULL) {
176 		if (strstr(buf, hugepages_total) == buf) {
177 			unsigned long long total = strtoull(buf + strlen(hugepages_total), NULL, 10);
178 			if (!total) {
179 				fprintf(stderr, "HUGETLB is not enabled in /proc/sys/vm/nr_hugepages\n");
180 				exit(KSFT_SKIP);
181 			}
182 		}
183 		if (strstr(buf, hugepagesize) == buf) {
184 			fclose(f);
185 			return strtoull(buf + strlen(hugepagesize), NULL, 10) << 10;
186 		}
187 	}
188 
189 	if (feof(f)) {
190 		fprintf(stderr, "HUGETLB is not configured in host kernel");
191 		exit(KSFT_SKIP);
192 	}
193 
194 	TEST_FAIL("Error in reading /proc/meminfo");
195 }
196 
197 #define ANON_FLAGS	(MAP_PRIVATE | MAP_ANONYMOUS)
198 #define ANON_HUGE_FLAGS	(ANON_FLAGS | MAP_HUGETLB)
199 
200 const struct vm_mem_backing_src_alias *vm_mem_backing_src_alias(uint32_t i)
201 {
202 	static const struct vm_mem_backing_src_alias aliases[] = {
203 		[VM_MEM_SRC_ANONYMOUS] = {
204 			.name = "anonymous",
205 			.flag = ANON_FLAGS,
206 		},
207 		[VM_MEM_SRC_ANONYMOUS_THP] = {
208 			.name = "anonymous_thp",
209 			.flag = ANON_FLAGS,
210 		},
211 		[VM_MEM_SRC_ANONYMOUS_HUGETLB] = {
212 			.name = "anonymous_hugetlb",
213 			.flag = ANON_HUGE_FLAGS,
214 		},
215 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_16KB] = {
216 			.name = "anonymous_hugetlb_16kb",
217 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_16KB,
218 		},
219 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_64KB] = {
220 			.name = "anonymous_hugetlb_64kb",
221 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_64KB,
222 		},
223 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_512KB] = {
224 			.name = "anonymous_hugetlb_512kb",
225 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_512KB,
226 		},
227 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_1MB] = {
228 			.name = "anonymous_hugetlb_1mb",
229 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_1MB,
230 		},
231 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_2MB] = {
232 			.name = "anonymous_hugetlb_2mb",
233 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_2MB,
234 		},
235 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_8MB] = {
236 			.name = "anonymous_hugetlb_8mb",
237 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_8MB,
238 		},
239 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_16MB] = {
240 			.name = "anonymous_hugetlb_16mb",
241 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_16MB,
242 		},
243 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_32MB] = {
244 			.name = "anonymous_hugetlb_32mb",
245 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_32MB,
246 		},
247 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_256MB] = {
248 			.name = "anonymous_hugetlb_256mb",
249 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_256MB,
250 		},
251 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_512MB] = {
252 			.name = "anonymous_hugetlb_512mb",
253 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_512MB,
254 		},
255 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_1GB] = {
256 			.name = "anonymous_hugetlb_1gb",
257 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_1GB,
258 		},
259 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_2GB] = {
260 			.name = "anonymous_hugetlb_2gb",
261 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_2GB,
262 		},
263 		[VM_MEM_SRC_ANONYMOUS_HUGETLB_16GB] = {
264 			.name = "anonymous_hugetlb_16gb",
265 			.flag = ANON_HUGE_FLAGS | MAP_HUGE_16GB,
266 		},
267 		[VM_MEM_SRC_SHMEM] = {
268 			.name = "shmem",
269 			.flag = MAP_SHARED,
270 		},
271 		[VM_MEM_SRC_SHARED_HUGETLB] = {
272 			.name = "shared_hugetlb",
273 			/*
274 			 * No MAP_HUGETLB, we use MFD_HUGETLB instead. Since
275 			 * we're using "file backed" memory, we need to specify
276 			 * this when the FD is created, not when the area is
277 			 * mapped.
278 			 */
279 			.flag = MAP_SHARED,
280 		},
281 	};
282 	_Static_assert(ARRAY_SIZE(aliases) == NUM_SRC_TYPES,
283 		       "Missing new backing src types?");
284 
285 	TEST_ASSERT(i < NUM_SRC_TYPES, "Backing src type ID %d too big", i);
286 
287 	return &aliases[i];
288 }
289 
290 #define MAP_HUGE_PAGE_SIZE(x) (1ULL << ((x >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK))
291 
292 size_t get_backing_src_pagesz(uint32_t i)
293 {
294 	uint32_t flag = vm_mem_backing_src_alias(i)->flag;
295 
296 	switch (i) {
297 	case VM_MEM_SRC_ANONYMOUS:
298 	case VM_MEM_SRC_SHMEM:
299 		return getpagesize();
300 	case VM_MEM_SRC_ANONYMOUS_THP:
301 		return get_trans_hugepagesz();
302 	case VM_MEM_SRC_ANONYMOUS_HUGETLB:
303 	case VM_MEM_SRC_SHARED_HUGETLB:
304 		return get_def_hugetlb_pagesz();
305 	default:
306 		return MAP_HUGE_PAGE_SIZE(flag);
307 	}
308 }
309 
310 bool is_backing_src_hugetlb(uint32_t i)
311 {
312 	return !!(vm_mem_backing_src_alias(i)->flag & MAP_HUGETLB);
313 }
314 
315 static void print_available_backing_src_types(const char *prefix)
316 {
317 	int i;
318 
319 	printf("%sAvailable backing src types:\n", prefix);
320 
321 	for (i = 0; i < NUM_SRC_TYPES; i++)
322 		printf("%s    %s\n", prefix, vm_mem_backing_src_alias(i)->name);
323 }
324 
325 void backing_src_help(const char *flag)
326 {
327 	printf(" %s: specify the type of memory that should be used to\n"
328 	       "     back the guest data region. (default: %s)\n",
329 	       flag, vm_mem_backing_src_alias(DEFAULT_VM_MEM_SRC)->name);
330 	print_available_backing_src_types("     ");
331 }
332 
333 enum vm_mem_backing_src_type parse_backing_src_type(const char *type_name)
334 {
335 	int i;
336 
337 	for (i = 0; i < NUM_SRC_TYPES; i++)
338 		if (!strcmp(type_name, vm_mem_backing_src_alias(i)->name))
339 			return i;
340 
341 	print_available_backing_src_types("");
342 	TEST_FAIL("Unknown backing src type: %s", type_name);
343 	return -1;
344 }
345 
346 long get_run_delay(void)
347 {
348 	char path[64];
349 	long val[2];
350 	FILE *fp;
351 
352 	sprintf(path, "/proc/%ld/schedstat", syscall(SYS_gettid));
353 	fp = fopen(path, "r");
354 	/* Return MIN_RUN_DELAY_NS upon failure just to be safe */
355 	if (fscanf(fp, "%ld %ld ", &val[0], &val[1]) < 2)
356 		val[1] = MIN_RUN_DELAY_NS;
357 	fclose(fp);
358 
359 	return val[1];
360 }
361 
362 int atoi_paranoid(const char *num_str)
363 {
364 	char *end_ptr;
365 	long num;
366 
367 	errno = 0;
368 	num = strtol(num_str, &end_ptr, 0);
369 	TEST_ASSERT(!errno, "strtol(\"%s\") failed", num_str);
370 	TEST_ASSERT(num_str != end_ptr,
371 		    "strtol(\"%s\") didn't find a valid integer.", num_str);
372 	TEST_ASSERT(*end_ptr == '\0',
373 		    "strtol(\"%s\") failed to parse trailing characters \"%s\".",
374 		    num_str, end_ptr);
375 	TEST_ASSERT(num >= INT_MIN && num <= INT_MAX,
376 		    "%ld not in range of [%d, %d]", num, INT_MIN, INT_MAX);
377 
378 	return num;
379 }
380