1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * arch_timer.c - Tests the arch timer IRQ functionality
4 *
5 * The guest's main thread configures the timer interrupt and waits
6 * for it to fire, with a timeout equal to the timer period.
7 * It asserts that the timeout doesn't exceed the timer period plus
8 * a user configurable error margin(default to 100us)
9 *
10 * On the other hand, upon receipt of an interrupt, the guest's interrupt
11 * handler validates the interrupt by checking if the architectural state
12 * is in compliance with the specifications.
13 *
14 * The test provides command-line options to configure the timer's
15 * period (-p), number of vCPUs (-n), iterations per stage (-i) and timer
16 * interrupt arrival error margin (-e). To stress-test the timer stack
17 * even more, an option to migrate the vCPUs across pCPUs (-m), at a
18 * particular rate, is also provided.
19 *
20 * Copyright (c) 2021, Google LLC.
21 */
22
23#define _GNU_SOURCE
24
25#include <stdlib.h>
26#include <pthread.h>
27#include <linux/sizes.h>
28#include <linux/bitmap.h>
29#include <sys/sysinfo.h>
30
31#include "timer_test.h"
32
33struct test_args test_args = {
34	.nr_vcpus = NR_VCPUS_DEF,
35	.nr_iter = NR_TEST_ITERS_DEF,
36	.timer_period_ms = TIMER_TEST_PERIOD_MS_DEF,
37	.migration_freq_ms = TIMER_TEST_MIGRATION_FREQ_MS,
38	.timer_err_margin_us = TIMER_TEST_ERR_MARGIN_US,
39	.reserved = 1,
40};
41
42struct kvm_vcpu *vcpus[KVM_MAX_VCPUS];
43struct test_vcpu_shared_data vcpu_shared_data[KVM_MAX_VCPUS];
44
45static pthread_t pt_vcpu_run[KVM_MAX_VCPUS];
46static unsigned long *vcpu_done_map;
47static pthread_mutex_t vcpu_done_map_lock;
48
49static void *test_vcpu_run(void *arg)
50{
51	unsigned int vcpu_idx = (unsigned long)arg;
52	struct ucall uc;
53	struct kvm_vcpu *vcpu = vcpus[vcpu_idx];
54	struct kvm_vm *vm = vcpu->vm;
55	struct test_vcpu_shared_data *shared_data = &vcpu_shared_data[vcpu_idx];
56
57	vcpu_run(vcpu);
58
59	/* Currently, any exit from guest is an indication of completion */
60	pthread_mutex_lock(&vcpu_done_map_lock);
61	__set_bit(vcpu_idx, vcpu_done_map);
62	pthread_mutex_unlock(&vcpu_done_map_lock);
63
64	switch (get_ucall(vcpu, &uc)) {
65	case UCALL_SYNC:
66	case UCALL_DONE:
67		break;
68	case UCALL_ABORT:
69		sync_global_from_guest(vm, *shared_data);
70		fprintf(stderr, "Guest assert failed,  vcpu %u; stage; %u; iter: %u\n",
71			vcpu_idx, shared_data->guest_stage, shared_data->nr_iter);
72		REPORT_GUEST_ASSERT(uc);
73		break;
74	default:
75		TEST_FAIL("Unexpected guest exit");
76	}
77
78	pr_info("PASS(vCPU-%d).\n", vcpu_idx);
79
80	return NULL;
81}
82
83static uint32_t test_get_pcpu(void)
84{
85	uint32_t pcpu;
86	unsigned int nproc_conf;
87	cpu_set_t online_cpuset;
88
89	nproc_conf = get_nprocs_conf();
90	sched_getaffinity(0, sizeof(cpu_set_t), &online_cpuset);
91
92	/* Randomly find an available pCPU to place a vCPU on */
93	do {
94		pcpu = rand() % nproc_conf;
95	} while (!CPU_ISSET(pcpu, &online_cpuset));
96
97	return pcpu;
98}
99
100static int test_migrate_vcpu(unsigned int vcpu_idx)
101{
102	int ret;
103	cpu_set_t cpuset;
104	uint32_t new_pcpu = test_get_pcpu();
105
106	CPU_ZERO(&cpuset);
107	CPU_SET(new_pcpu, &cpuset);
108
109	pr_debug("Migrating vCPU: %u to pCPU: %u\n", vcpu_idx, new_pcpu);
110
111	ret = pthread_setaffinity_np(pt_vcpu_run[vcpu_idx],
112				     sizeof(cpuset), &cpuset);
113
114	/* Allow the error where the vCPU thread is already finished */
115	TEST_ASSERT(ret == 0 || ret == ESRCH,
116		    "Failed to migrate the vCPU:%u to pCPU: %u; ret: %d",
117		    vcpu_idx, new_pcpu, ret);
118
119	return ret;
120}
121
122static void *test_vcpu_migration(void *arg)
123{
124	unsigned int i, n_done;
125	bool vcpu_done;
126
127	do {
128		usleep(msecs_to_usecs(test_args.migration_freq_ms));
129
130		for (n_done = 0, i = 0; i < test_args.nr_vcpus; i++) {
131			pthread_mutex_lock(&vcpu_done_map_lock);
132			vcpu_done = test_bit(i, vcpu_done_map);
133			pthread_mutex_unlock(&vcpu_done_map_lock);
134
135			if (vcpu_done) {
136				n_done++;
137				continue;
138			}
139
140			test_migrate_vcpu(i);
141		}
142	} while (test_args.nr_vcpus != n_done);
143
144	return NULL;
145}
146
147static void test_run(struct kvm_vm *vm)
148{
149	pthread_t pt_vcpu_migration;
150	unsigned int i;
151	int ret;
152
153	pthread_mutex_init(&vcpu_done_map_lock, NULL);
154	vcpu_done_map = bitmap_zalloc(test_args.nr_vcpus);
155	TEST_ASSERT(vcpu_done_map, "Failed to allocate vcpu done bitmap");
156
157	for (i = 0; i < (unsigned long)test_args.nr_vcpus; i++) {
158		ret = pthread_create(&pt_vcpu_run[i], NULL, test_vcpu_run,
159				     (void *)(unsigned long)i);
160		TEST_ASSERT(!ret, "Failed to create vCPU-%d pthread", i);
161	}
162
163	/* Spawn a thread to control the vCPU migrations */
164	if (test_args.migration_freq_ms) {
165		srand(time(NULL));
166
167		ret = pthread_create(&pt_vcpu_migration, NULL,
168					test_vcpu_migration, NULL);
169		TEST_ASSERT(!ret, "Failed to create the migration pthread");
170	}
171
172
173	for (i = 0; i < test_args.nr_vcpus; i++)
174		pthread_join(pt_vcpu_run[i], NULL);
175
176	if (test_args.migration_freq_ms)
177		pthread_join(pt_vcpu_migration, NULL);
178
179	bitmap_free(vcpu_done_map);
180}
181
182static void test_print_help(char *name)
183{
184	pr_info("Usage: %s [-h] [-n nr_vcpus] [-i iterations] [-p timer_period_ms]\n"
185		"\t\t    [-m migration_freq_ms] [-o counter_offset]\n"
186		"\t\t    [-e timer_err_margin_us]\n", name);
187	pr_info("\t-n: Number of vCPUs to configure (default: %u; max: %u)\n",
188		NR_VCPUS_DEF, KVM_MAX_VCPUS);
189	pr_info("\t-i: Number of iterations per stage (default: %u)\n",
190		NR_TEST_ITERS_DEF);
191	pr_info("\t-p: Periodicity (in ms) of the guest timer (default: %u)\n",
192		TIMER_TEST_PERIOD_MS_DEF);
193	pr_info("\t-m: Frequency (in ms) of vCPUs to migrate to different pCPU. 0 to turn off (default: %u)\n",
194		TIMER_TEST_MIGRATION_FREQ_MS);
195	pr_info("\t-o: Counter offset (in counter cycles, default: 0) [aarch64-only]\n");
196	pr_info("\t-e: Interrupt arrival error margin (in us) of the guest timer (default: %u)\n",
197		TIMER_TEST_ERR_MARGIN_US);
198	pr_info("\t-h: print this help screen\n");
199}
200
201static bool parse_args(int argc, char *argv[])
202{
203	int opt;
204
205	while ((opt = getopt(argc, argv, "hn:i:p:m:o:e:")) != -1) {
206		switch (opt) {
207		case 'n':
208			test_args.nr_vcpus = atoi_positive("Number of vCPUs", optarg);
209			if (test_args.nr_vcpus > KVM_MAX_VCPUS) {
210				pr_info("Max allowed vCPUs: %u\n",
211					KVM_MAX_VCPUS);
212				goto err;
213			}
214			break;
215		case 'i':
216			test_args.nr_iter = atoi_positive("Number of iterations", optarg);
217			break;
218		case 'p':
219			test_args.timer_period_ms = atoi_positive("Periodicity", optarg);
220			break;
221		case 'm':
222			test_args.migration_freq_ms = atoi_non_negative("Frequency", optarg);
223			break;
224		case 'e':
225			test_args.timer_err_margin_us = atoi_non_negative("Error Margin", optarg);
226			break;
227		case 'o':
228			test_args.counter_offset = strtol(optarg, NULL, 0);
229			test_args.reserved = 0;
230			break;
231		case 'h':
232		default:
233			goto err;
234		}
235	}
236
237	return true;
238
239err:
240	test_print_help(argv[0]);
241	return false;
242}
243
244int main(int argc, char *argv[])
245{
246	struct kvm_vm *vm;
247
248	if (!parse_args(argc, argv))
249		exit(KSFT_SKIP);
250
251	__TEST_REQUIRE(!test_args.migration_freq_ms || get_nprocs() >= 2,
252		       "At least two physical CPUs needed for vCPU migration");
253
254	vm = test_vm_create();
255	test_run(vm);
256	test_vm_cleanup(vm);
257
258	return 0;
259}
260