xen_shinfo_test.c 30.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// SPDX-License-Identifier: GPL-2.0-only
/*
 * svm_vmcall_test
 *
 * Copyright © 2021 Amazon.com, Inc. or its affiliates.
 *
 * Xen shared_info / pvclock testing
 */

#include "test_util.h"
#include "kvm_util.h"
#include "processor.h"

#include <stdint.h>
#include <time.h>
16
#include <sched.h>
17
#include <signal.h>
18
#include <pthread.h>
19 20

#include <sys/eventfd.h>
21

22 23 24
/* Defined in include/linux/kvm_types.h */
#define GPA_INVALID		(~(ulong)0)

25
#define SHINFO_REGION_GVA	0xc0000000ULL
26 27 28
#define SHINFO_REGION_GPA	0xc0000000ULL
#define SHINFO_REGION_SLOT	10

29
#define DUMMY_REGION_GPA	(SHINFO_REGION_GPA + (3 * PAGE_SIZE))
30 31 32
#define DUMMY_REGION_SLOT	11

#define SHINFO_ADDR	(SHINFO_REGION_GPA)
33
#define VCPU_INFO_ADDR	(SHINFO_REGION_GPA + 0x40)
34 35
#define PVTIME_ADDR	(SHINFO_REGION_GPA + PAGE_SIZE)
#define RUNSTATE_ADDR	(SHINFO_REGION_GPA + PAGE_SIZE + PAGE_SIZE - 15)
36

37
#define SHINFO_VADDR	(SHINFO_REGION_GVA)
38
#define VCPU_INFO_VADDR	(SHINFO_REGION_GVA + 0x40)
39
#define RUNSTATE_VADDR	(SHINFO_REGION_GVA + PAGE_SIZE + PAGE_SIZE - 15)
40 41

#define EVTCHN_VECTOR	0x10
42

43 44 45 46
#define EVTCHN_TEST1 15
#define EVTCHN_TEST2 66
#define EVTCHN_TIMER 13

47 48
#define XEN_HYPERCALL_MSR	0x40000000

49 50
#define MIN_STEAL_TIME		50000

51 52
#define SHINFO_RACE_TIMEOUT	2	/* seconds */

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#define __HYPERVISOR_set_timer_op	15
#define __HYPERVISOR_sched_op		29
#define __HYPERVISOR_event_channel_op	32

#define SCHEDOP_poll			3

#define EVTCHNOP_send			4

#define EVTCHNSTAT_interdomain		2

struct evtchn_send {
	u32 port;
};

struct sched_poll {
	u32 *ports;
	unsigned int nr_ports;
	u64 timeout;
};

73
struct pvclock_vcpu_time_info {
74 75 76 77 78 79 80 81
	u32   version;
	u32   pad0;
	u64   tsc_timestamp;
	u64   system_time;
	u32   tsc_to_system_mul;
	s8    tsc_shift;
	u8    flags;
	u8    pad[2];
82 83 84
} __attribute__((__packed__)); /* 32 bytes */

struct pvclock_wall_clock {
85 86 87
	u32   version;
	u32   sec;
	u32   nsec;
88 89
} __attribute__((__packed__));

90
struct vcpu_runstate_info {
91 92 93
	uint32_t state;
	uint64_t state_entry_time;
	uint64_t time[5]; /* Extra field for overrun check */
94 95
};

96 97 98 99 100 101
struct compat_vcpu_runstate_info {
	uint32_t state;
	uint64_t state_entry_time;
	uint64_t time[5];
} __attribute__((__packed__));;

102
struct arch_vcpu_info {
103 104
	unsigned long cr2;
	unsigned long pad; /* sizeof(vcpu_info_t) == 64 */
105 106 107
};

struct vcpu_info {
108 109 110 111 112
	uint8_t evtchn_upcall_pending;
	uint8_t evtchn_upcall_mask;
	unsigned long evtchn_pending_sel;
	struct arch_vcpu_info arch;
	struct pvclock_vcpu_time_info time;
113 114
}; /* 64 bytes (x86) */

115 116 117 118 119 120 121 122 123
struct shared_info {
	struct vcpu_info vcpu_info[32];
	unsigned long evtchn_pending[64];
	unsigned long evtchn_mask[64];
	struct pvclock_wall_clock wc;
	uint32_t wc_sec_hi;
	/* arch_shared_info here */
};

124 125 126 127 128
#define RUNSTATE_running  0
#define RUNSTATE_runnable 1
#define RUNSTATE_blocked  2
#define RUNSTATE_offline  3

129 130 131 132 133 134 135 136 137 138 139 140
static const char *runstate_names[] = {
	"running",
	"runnable",
	"blocked",
	"offline"
};

struct {
	struct kvm_irq_routing info;
	struct kvm_irq_routing_entry entries[2];
} irq_routes;

141
static volatile bool guest_saw_irq;
142

143 144 145 146
static void evtchn_handler(struct ex_regs *regs)
{
	struct vcpu_info *vi = (void *)VCPU_INFO_VADDR;
	vi->evtchn_upcall_pending = 0;
147
	vi->evtchn_pending_sel = 0;
148
	guest_saw_irq = true;
149 150 151 152

	GUEST_SYNC(0x20);
}

153 154 155 156 157 158 159
static void guest_wait_for_irq(void)
{
	while (!guest_saw_irq)
		__asm__ __volatile__ ("rep nop" : : : "memory");
	guest_saw_irq = false;
}

160 161
static void guest_code(void)
{
162
	struct vcpu_runstate_info *rs = (void *)RUNSTATE_VADDR;
163
	int i;
164

165 166 167 168 169 170 171 172
	__asm__ __volatile__(
		"sti\n"
		"nop\n"
	);

	/* Trigger an interrupt injection */
	GUEST_SYNC(0);

173 174
	guest_wait_for_irq();

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
	/* Test having the host set runstates manually */
	GUEST_SYNC(RUNSTATE_runnable);
	GUEST_ASSERT(rs->time[RUNSTATE_runnable] != 0);
	GUEST_ASSERT(rs->state == 0);

	GUEST_SYNC(RUNSTATE_blocked);
	GUEST_ASSERT(rs->time[RUNSTATE_blocked] != 0);
	GUEST_ASSERT(rs->state == 0);

	GUEST_SYNC(RUNSTATE_offline);
	GUEST_ASSERT(rs->time[RUNSTATE_offline] != 0);
	GUEST_ASSERT(rs->state == 0);

	/* Test runstate time adjust */
	GUEST_SYNC(4);
	GUEST_ASSERT(rs->time[RUNSTATE_blocked] == 0x5a);
	GUEST_ASSERT(rs->time[RUNSTATE_offline] == 0x6b6b);

	/* Test runstate time set */
	GUEST_SYNC(5);
	GUEST_ASSERT(rs->state_entry_time >= 0x8000);
	GUEST_ASSERT(rs->time[RUNSTATE_runnable] == 0);
	GUEST_ASSERT(rs->time[RUNSTATE_blocked] == 0x6b6b);
	GUEST_ASSERT(rs->time[RUNSTATE_offline] == 0x5a);

	/* sched_yield() should result in some 'runnable' time */
	GUEST_SYNC(6);
	GUEST_ASSERT(rs->time[RUNSTATE_runnable] >= MIN_STEAL_TIME);

204 205 206 207 208 209 210 211 212 213 214
	/* Attempt to deliver a *masked* interrupt */
	GUEST_SYNC(7);

	/* Wait until we see the bit set */
	struct shared_info *si = (void *)SHINFO_VADDR;
	while (!si->evtchn_pending[0])
		__asm__ __volatile__ ("rep nop" : : : "memory");

	/* Now deliver an *unmasked* interrupt */
	GUEST_SYNC(8);

215
	guest_wait_for_irq();
216 217 218 219

	/* Change memslots and deliver an interrupt */
	GUEST_SYNC(9);

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	guest_wait_for_irq();

	/* Deliver event channel with KVM_XEN_HVM_EVTCHN_SEND */
	GUEST_SYNC(10);

	guest_wait_for_irq();

	GUEST_SYNC(11);

	/* Our turn. Deliver event channel (to ourselves) with
	 * EVTCHNOP_send hypercall. */
	unsigned long rax;
	struct evtchn_send s = { .port = 127 };
	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_event_channel_op),
			      "D" (EVTCHNOP_send),
			      "S" (&s));

	GUEST_ASSERT(rax == 0);

	guest_wait_for_irq();

	GUEST_SYNC(12);

	/* Deliver "outbound" event channel to an eventfd which
	 * happens to be one of our own irqfds. */
	s.port = 197;
	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_event_channel_op),
			      "D" (EVTCHNOP_send),
			      "S" (&s));

	GUEST_ASSERT(rax == 0);

	guest_wait_for_irq();

	GUEST_SYNC(13);

	/* Set a timer 100ms in the future. */
	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_set_timer_op),
			      "D" (rs->state_entry_time + 100000000));
	GUEST_ASSERT(rax == 0);

	GUEST_SYNC(14);

	/* Now wait for the timer */
	guest_wait_for_irq();

	GUEST_SYNC(15);

	/* The host has 'restored' the timer. Just wait for it. */
	guest_wait_for_irq();

	GUEST_SYNC(16);

	/* Poll for an event channel port which is already set */
	u32 ports[1] = { EVTCHN_TIMER };
	struct sched_poll p = {
		.ports = ports,
		.nr_ports = 1,
		.timeout = 0,
	};

	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_sched_op),
			      "D" (SCHEDOP_poll),
			      "S" (&p));

	GUEST_ASSERT(rax == 0);

	GUEST_SYNC(17);

	/* Poll for an unset port and wait for the timeout. */
	p.timeout = 100000000;
	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_sched_op),
			      "D" (SCHEDOP_poll),
			      "S" (&p));

	GUEST_ASSERT(rax == 0);

	GUEST_SYNC(18);

	/* A timer will wake the masked port we're waiting on, while we poll */
	p.timeout = 0;
	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_sched_op),
			      "D" (SCHEDOP_poll),
			      "S" (&p));

	GUEST_ASSERT(rax == 0);

	GUEST_SYNC(19);

	/* A timer wake an *unmasked* port which should wake us with an
	 * actual interrupt, while we're polling on a different port. */
	ports[0]++;
	p.timeout = 0;
	__asm__ __volatile__ ("vmcall" :
			      "=a" (rax) :
			      "a" (__HYPERVISOR_sched_op),
			      "D" (SCHEDOP_poll),
			      "S" (&p));

	GUEST_ASSERT(rax == 0);

	guest_wait_for_irq();

	GUEST_SYNC(20);
336 337 338 339 340

	/* Timer should have fired already */
	guest_wait_for_irq();

	GUEST_SYNC(21);
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	/* Racing host ioctls */

	guest_wait_for_irq();

	GUEST_SYNC(22);
	/* Racing vmcall against host ioctl */

	ports[0] = 0;

	p = (struct sched_poll) {
		.ports = ports,
		.nr_ports = 1,
		.timeout = 0
	};

wait_for_timer:
	/*
	 * Poll for a timer wake event while the worker thread is mucking with
	 * the shared info.  KVM XEN drops timer IRQs if the shared info is
	 * invalid when the timer expires.  Arbitrarily poll 100 times before
	 * giving up and asking the VMM to re-arm the timer.  100 polls should
	 * consume enough time to beat on KVM without taking too long if the
	 * timer IRQ is dropped due to an invalid event channel.
	 */
	for (i = 0; i < 100 && !guest_saw_irq; i++)
		asm volatile("vmcall"
			     : "=a" (rax)
			     : "a" (__HYPERVISOR_sched_op),
			       "D" (SCHEDOP_poll),
			       "S" (&p)
			     : "memory");

	/*
	 * Re-send the timer IRQ if it was (likely) dropped due to the timer
	 * expiring while the event channel was invalid.
	 */
	if (!guest_saw_irq) {
		GUEST_SYNC(23);
		goto wait_for_timer;
	}
	guest_saw_irq = false;

	GUEST_SYNC(24);
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
}

static int cmp_timespec(struct timespec *a, struct timespec *b)
{
	if (a->tv_sec > b->tv_sec)
		return 1;
	else if (a->tv_sec < b->tv_sec)
		return -1;
	else if (a->tv_nsec > b->tv_nsec)
		return 1;
	else if (a->tv_nsec < b->tv_nsec)
		return -1;
	else
		return 0;
}
399 400 401

static struct vcpu_info *vinfo;
static struct kvm_vcpu *vcpu;
402

403 404
static void handle_alrm(int sig)
{
405 406
	if (vinfo)
		printf("evtchn_upcall_pending 0x%x\n", vinfo->evtchn_upcall_pending);
407
	vcpu_dump(stdout, vcpu, 0);
408 409 410
	TEST_FAIL("IRQ delivery timed out");
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
static void *juggle_shinfo_state(void *arg)
{
	struct kvm_vm *vm = (struct kvm_vm *)arg;

	struct kvm_xen_hvm_attr cache_init = {
		.type = KVM_XEN_ATTR_TYPE_SHARED_INFO,
		.u.shared_info.gfn = SHINFO_REGION_GPA / PAGE_SIZE
	};

	struct kvm_xen_hvm_attr cache_destroy = {
		.type = KVM_XEN_ATTR_TYPE_SHARED_INFO,
		.u.shared_info.gfn = GPA_INVALID
	};

	for (;;) {
		__vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &cache_init);
		__vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &cache_destroy);
		pthread_testcancel();
	};

	return NULL;
}

434 435 436
int main(int argc, char *argv[])
{
	struct timespec min_ts, max_ts, vm_ts;
437
	struct kvm_vm *vm;
438
	pthread_t thread;
439
	bool verbose;
440
	int ret;
441 442 443

	verbose = argc > 1 && (!strncmp(argv[1], "-v", 3) ||
			       !strncmp(argv[1], "--verbose", 10));
444

445
	int xen_caps = kvm_check_cap(KVM_CAP_XEN_HVM);
446
	TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_SHARED_INFO);
447

448
	bool do_runstate_tests = !!(xen_caps & KVM_XEN_HVM_CONFIG_RUNSTATE);
449
	bool do_runstate_flag = !!(xen_caps & KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG);
450
	bool do_eventfd_tests = !!(xen_caps & KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL);
451
	bool do_evtchn_tests = do_eventfd_tests && !!(xen_caps & KVM_XEN_HVM_CONFIG_EVTCHN_SEND);
452

453 454
	clock_gettime(CLOCK_REALTIME, &min_ts);

455
	vm = vm_create_with_one_vcpu(&vcpu, guest_code);
456 457 458

	/* Map a region for the shared_info page */
	vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
459 460
				    SHINFO_REGION_GPA, SHINFO_REGION_SLOT, 3, 0);
	virt_map(vm, SHINFO_REGION_GVA, SHINFO_REGION_GPA, 3);
461

462 463 464 465 466
	struct shared_info *shinfo = addr_gpa2hva(vm, SHINFO_VADDR);

	int zero_fd = open("/dev/zero", O_RDONLY);
	TEST_ASSERT(zero_fd != -1, "Failed to open /dev/zero");

467 468 469 470
	struct kvm_xen_hvm_config hvmc = {
		.flags = KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL,
		.msr = XEN_HYPERCALL_MSR,
	};
471 472 473

	/* Let the kernel know that we *will* use it for sending all
	 * event channels, which lets it intercept SCHEDOP_poll */
474
	if (do_evtchn_tests)
475 476
		hvmc.flags |= KVM_XEN_HVM_CONFIG_EVTCHN_SEND;

477 478 479 480 481 482 483 484
	vm_ioctl(vm, KVM_XEN_HVM_CONFIG, &hvmc);

	struct kvm_xen_hvm_attr lm = {
		.type = KVM_XEN_ATTR_TYPE_LONG_MODE,
		.u.long_mode = 1,
	};
	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &lm);

485 486 487 488 489 490 491 492 493 494 495 496 497
	if (do_runstate_flag) {
		struct kvm_xen_hvm_attr ruf = {
			.type = KVM_XEN_ATTR_TYPE_RUNSTATE_UPDATE_FLAG,
			.u.runstate_update_flag = 1,
		};
		vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &ruf);

		ruf.u.runstate_update_flag = 0;
		vm_ioctl(vm, KVM_XEN_HVM_GET_ATTR, &ruf);
		TEST_ASSERT(ruf.u.runstate_update_flag == 1,
			    "Failed to read back RUNSTATE_UPDATE_FLAG attr");
	}

498 499 500 501 502 503
	struct kvm_xen_hvm_attr ha = {
		.type = KVM_XEN_ATTR_TYPE_SHARED_INFO,
		.u.shared_info.gfn = SHINFO_REGION_GPA / PAGE_SIZE,
	};
	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &ha);

504 505 506 507 508 509 510 511 512 513
	/*
	 * Test what happens when the HVA of the shinfo page is remapped after
	 * the kernel has a reference to it. But make sure we copy the clock
	 * info over since that's only set at setup time, and we test it later.
	 */
	struct pvclock_wall_clock wc_copy = shinfo->wc;
	void *m = mmap(shinfo, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_FIXED|MAP_PRIVATE, zero_fd, 0);
	TEST_ASSERT(m == shinfo, "Failed to map /dev/zero over shared info");
	shinfo->wc = wc_copy;

514 515
	struct kvm_xen_vcpu_attr vi = {
		.type = KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO,
516
		.u.gpa = VCPU_INFO_ADDR,
517
	};
518
	vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &vi);
519 520 521 522 523

	struct kvm_xen_vcpu_attr pvclock = {
		.type = KVM_XEN_VCPU_ATTR_TYPE_VCPU_TIME_INFO,
		.u.gpa = PVTIME_ADDR,
	};
524
	vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &pvclock);
525

526 527 528 529 530 531 532
	struct kvm_xen_hvm_attr vec = {
		.type = KVM_XEN_ATTR_TYPE_UPCALL_VECTOR,
		.u.vector = EVTCHN_VECTOR,
	};
	vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &vec);

	vm_init_descriptor_tables(vm);
533
	vcpu_init_descriptor_tables(vcpu);
534 535
	vm_install_exception_handler(vm, EVTCHN_VECTOR, evtchn_handler);

536 537 538 539 540
	if (do_runstate_tests) {
		struct kvm_xen_vcpu_attr st = {
			.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR,
			.u.gpa = RUNSTATE_ADDR,
		};
541
		vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &st);
542 543
	}

544 545 546 547 548 549 550 551
	int irq_fd[2] = { -1, -1 };

	if (do_eventfd_tests) {
		irq_fd[0] = eventfd(0, 0);
		irq_fd[1] = eventfd(0, 0);

		/* Unexpected, but not a KVM failure */
		if (irq_fd[0] == -1 || irq_fd[1] == -1)
552
			do_evtchn_tests = do_eventfd_tests = false;
553 554 555 556 557 558 559
	}

	if (do_eventfd_tests) {
		irq_routes.info.nr = 2;

		irq_routes.entries[0].gsi = 32;
		irq_routes.entries[0].type = KVM_IRQ_ROUTING_XEN_EVTCHN;
560
		irq_routes.entries[0].u.xen_evtchn.port = EVTCHN_TEST1;
561
		irq_routes.entries[0].u.xen_evtchn.vcpu = vcpu->id;
562 563 564 565
		irq_routes.entries[0].u.xen_evtchn.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;

		irq_routes.entries[1].gsi = 33;
		irq_routes.entries[1].type = KVM_IRQ_ROUTING_XEN_EVTCHN;
566
		irq_routes.entries[1].u.xen_evtchn.port = EVTCHN_TEST2;
567
		irq_routes.entries[1].u.xen_evtchn.vcpu = vcpu->id;
568 569
		irq_routes.entries[1].u.xen_evtchn.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;

570
		vm_ioctl(vm, KVM_SET_GSI_ROUTING, &irq_routes.info);
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586

		struct kvm_irqfd ifd = { };

		ifd.fd = irq_fd[0];
		ifd.gsi = 32;
		vm_ioctl(vm, KVM_IRQFD, &ifd);

		ifd.fd = irq_fd[1];
		ifd.gsi = 33;
		vm_ioctl(vm, KVM_IRQFD, &ifd);

		struct sigaction sa = { };
		sa.sa_handler = handle_alrm;
		sigaction(SIGALRM, &sa, NULL);
	}

587 588 589 590 591 592 593 594 595 596 597 598 599 600
	struct kvm_xen_vcpu_attr tmr = {
		.type = KVM_XEN_VCPU_ATTR_TYPE_TIMER,
		.u.timer.port = EVTCHN_TIMER,
		.u.timer.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL,
		.u.timer.expires_ns = 0
	};

	if (do_evtchn_tests) {
		struct kvm_xen_hvm_attr inj = {
			.type = KVM_XEN_ATTR_TYPE_EVTCHN,
			.u.evtchn.send_port = 127,
			.u.evtchn.type = EVTCHNSTAT_interdomain,
			.u.evtchn.flags = 0,
			.u.evtchn.deliver.port.port = EVTCHN_TEST1,
601
			.u.evtchn.deliver.port.vcpu = vcpu->id + 1,
602 603 604 605 606 607
			.u.evtchn.deliver.port.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL,
		};
		vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &inj);

		/* Test migration to a different vCPU */
		inj.u.evtchn.flags = KVM_XEN_EVTCHN_UPDATE;
608
		inj.u.evtchn.deliver.port.vcpu = vcpu->id;
609 610 611 612 613 614 615 616
		vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &inj);

		inj.u.evtchn.send_port = 197;
		inj.u.evtchn.deliver.eventfd.port = 0;
		inj.u.evtchn.deliver.eventfd.fd = irq_fd[1];
		inj.u.evtchn.flags = 0;
		vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &inj);

617
		vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
618 619
	}
	vinfo = addr_gpa2hva(vm, VCPU_INFO_VADDR);
620 621
	vinfo->evtchn_upcall_pending = 0;

622
	struct vcpu_runstate_info *rs = addr_gpa2hva(vm, RUNSTATE_ADDR);
623 624
	rs->state = 0x5a;

625 626
	bool evtchn_irq_expected = false;

627
	for (;;) {
628
		volatile struct kvm_run *run = vcpu->run;
629 630
		struct ucall uc;

631
		vcpu_run(vcpu);
632 633 634 635 636 637

		TEST_ASSERT(run->exit_reason == KVM_EXIT_IO,
			    "Got exit_reason other than KVM_EXIT_IO: %u (%s)\n",
			    run->exit_reason,
			    exit_reason_str(run->exit_reason));

638
		switch (get_ucall(vcpu, &uc)) {
639
		case UCALL_ABORT:
640
			REPORT_GUEST_ASSERT(uc);
641
			/* NOT REACHED */
642 643 644 645
		case UCALL_SYNC: {
			struct kvm_xen_vcpu_attr rst;
			long rundelay;

646 647 648 649
			if (do_runstate_tests)
				TEST_ASSERT(rs->state_entry_time == rs->time[0] +
					    rs->time[1] + rs->time[2] + rs->time[3],
					    "runstate times don't add up");
650 651

			switch (uc.args[1]) {
652
			case 0:
653 654
				if (verbose)
					printf("Delivering evtchn upcall\n");
655 656 657 658 659 660 661 662
				evtchn_irq_expected = true;
				vinfo->evtchn_upcall_pending = 1;
				break;

			case RUNSTATE_runnable...RUNSTATE_offline:
				TEST_ASSERT(!evtchn_irq_expected, "Event channel IRQ not seen");
				if (!do_runstate_tests)
					goto done;
663 664
				if (verbose)
					printf("Testing runstate %s\n", runstate_names[uc.args[1]]);
665 666
				rst.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT;
				rst.u.runstate.state = uc.args[1];
667
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &rst);
668
				break;
669

670
			case 4:
671 672
				if (verbose)
					printf("Testing RUNSTATE_ADJUST\n");
673 674 675 676 677 678 679 680 681
				rst.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST;
				memset(&rst.u, 0, sizeof(rst.u));
				rst.u.runstate.state = (uint64_t)-1;
				rst.u.runstate.time_blocked =
					0x5a - rs->time[RUNSTATE_blocked];
				rst.u.runstate.time_offline =
					0x6b6b - rs->time[RUNSTATE_offline];
				rst.u.runstate.time_runnable = -rst.u.runstate.time_blocked -
					rst.u.runstate.time_offline;
682
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &rst);
683 684 685
				break;

			case 5:
686 687
				if (verbose)
					printf("Testing RUNSTATE_DATA\n");
688 689 690 691 692 693
				rst.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA;
				memset(&rst.u, 0, sizeof(rst.u));
				rst.u.runstate.state = RUNSTATE_running;
				rst.u.runstate.state_entry_time = 0x6b6b + 0x5a;
				rst.u.runstate.time_blocked = 0x6b6b;
				rst.u.runstate.time_offline = 0x5a;
694
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &rst);
695
				break;
696

697
			case 6:
698 699
				if (verbose)
					printf("Testing steal time\n");
700 701 702 703 704 705
				/* Yield until scheduler delay exceeds target */
				rundelay = get_run_delay() + MIN_STEAL_TIME;
				do {
					sched_yield();
				} while (get_run_delay() < rundelay);
				break;
706 707 708 709 710 711

			case 7:
				if (!do_eventfd_tests)
					goto done;
				if (verbose)
					printf("Testing masked event channel\n");
712
				shinfo->evtchn_mask[0] = 1UL << EVTCHN_TEST1;
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
				eventfd_write(irq_fd[0], 1UL);
				alarm(1);
				break;

			case 8:
				if (verbose)
					printf("Testing unmasked event channel\n");
				/* Unmask that, but deliver the other one */
				shinfo->evtchn_pending[0] = 0;
				shinfo->evtchn_mask[0] = 0;
				eventfd_write(irq_fd[1], 1UL);
				evtchn_irq_expected = true;
				alarm(1);
				break;

			case 9:
729 730 731
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
				shinfo->evtchn_pending[1] = 0;
732 733 734 735 736 737 738 739 740
				if (verbose)
					printf("Testing event channel after memslot change\n");
				vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
							    DUMMY_REGION_GPA, DUMMY_REGION_SLOT, 1, 0);
				eventfd_write(irq_fd[0], 1UL);
				evtchn_irq_expected = true;
				alarm(1);
				break;

741 742 743 744 745 746 747 748 749 750 751 752
			case 10:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
				if (!do_evtchn_tests)
					goto done;

				shinfo->evtchn_pending[0] = 0;
				if (verbose)
					printf("Testing injection with KVM_XEN_HVM_EVTCHN_SEND\n");

				struct kvm_irq_routing_xen_evtchn e;
				e.port = EVTCHN_TEST2;
753
				e.vcpu = vcpu->id;
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
				e.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL;

				vm_ioctl(vm, KVM_XEN_HVM_EVTCHN_SEND, &e);
				evtchn_irq_expected = true;
				alarm(1);
				break;

			case 11:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
				shinfo->evtchn_pending[1] = 0;

				if (verbose)
					printf("Testing guest EVTCHNOP_send direct to evtchn\n");
				evtchn_irq_expected = true;
				alarm(1);
				break;

			case 12:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
				shinfo->evtchn_pending[0] = 0;

				if (verbose)
					printf("Testing guest EVTCHNOP_send to eventfd\n");
				evtchn_irq_expected = true;
				alarm(1);
				break;

			case 13:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
				shinfo->evtchn_pending[1] = 0;

				if (verbose)
					printf("Testing guest oneshot timer\n");
				break;

			case 14:
				memset(&tmr, 0, sizeof(tmr));
794
				tmr.type = KVM_XEN_VCPU_ATTR_TYPE_TIMER;
795
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_GET_ATTR, &tmr);
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
				TEST_ASSERT(tmr.u.timer.port == EVTCHN_TIMER,
					    "Timer port not returned");
				TEST_ASSERT(tmr.u.timer.priority == KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL,
					    "Timer priority not returned");
				TEST_ASSERT(tmr.u.timer.expires_ns > rs->state_entry_time,
					    "Timer expiry not returned");
				evtchn_irq_expected = true;
				alarm(1);
				break;

			case 15:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
				shinfo->evtchn_pending[0] = 0;

				if (verbose)
					printf("Testing restored oneshot timer\n");

814
				tmr.u.timer.expires_ns = rs->state_entry_time + 100000000;
815
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
				evtchn_irq_expected = true;
				alarm(1);
				break;

			case 16:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");

				if (verbose)
					printf("Testing SCHEDOP_poll with already pending event\n");
				shinfo->evtchn_pending[0] = shinfo->evtchn_mask[0] = 1UL << EVTCHN_TIMER;
				alarm(1);
				break;

			case 17:
				if (verbose)
					printf("Testing SCHEDOP_poll timeout\n");
				shinfo->evtchn_pending[0] = 0;
				alarm(1);
				break;

			case 18:
				if (verbose)
					printf("Testing SCHEDOP_poll wake on masked event\n");

841
				tmr.u.timer.expires_ns = rs->state_entry_time + 100000000;
842
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
843
				alarm(1);
844 845 846 847 848 849 850 851
				break;

			case 19:
				shinfo->evtchn_pending[0] = shinfo->evtchn_mask[0] = 0;
				if (verbose)
					printf("Testing SCHEDOP_poll wake on unmasked event\n");

				evtchn_irq_expected = true;
852
				tmr.u.timer.expires_ns = rs->state_entry_time + 100000000;
853
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
854 855 856

				/* Read it back and check the pending time is reported correctly */
				tmr.u.timer.expires_ns = 0;
857
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_GET_ATTR, &tmr);
858 859 860
				TEST_ASSERT(tmr.u.timer.expires_ns == rs->state_entry_time + 100000000,
					    "Timer not reported pending");
				alarm(1);
861 862 863 864 865
				break;

			case 20:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
866
				/* Read timer and check it is no longer pending */
867
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_GET_ATTR, &tmr);
868 869 870 871 872 873 874 875
				TEST_ASSERT(!tmr.u.timer.expires_ns, "Timer still reported pending");

				shinfo->evtchn_pending[0] = 0;
				if (verbose)
					printf("Testing timer in the past\n");

				evtchn_irq_expected = true;
				tmr.u.timer.expires_ns = rs->state_entry_time - 100000000ULL;
876
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
877 878 879 880 881 882
				alarm(1);
				break;

			case 21:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
				alarm(0);

				if (verbose)
					printf("Testing shinfo lock corruption (KVM_XEN_HVM_EVTCHN_SEND)\n");

				ret = pthread_create(&thread, NULL, &juggle_shinfo_state, (void *)vm);
				TEST_ASSERT(ret == 0, "pthread_create() failed: %s", strerror(ret));

				struct kvm_irq_routing_xen_evtchn uxe = {
					.port = 1,
					.vcpu = vcpu->id,
					.priority = KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL
				};

				evtchn_irq_expected = true;
				for (time_t t = time(NULL) + SHINFO_RACE_TIMEOUT; time(NULL) < t;)
					__vm_ioctl(vm, KVM_XEN_HVM_EVTCHN_SEND, &uxe);
				break;

			case 22:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");

				if (verbose)
					printf("Testing shinfo lock corruption (SCHEDOP_poll)\n");

				shinfo->evtchn_pending[0] = 1;

				evtchn_irq_expected = true;
				tmr.u.timer.expires_ns = rs->state_entry_time +
							 SHINFO_RACE_TIMEOUT * 1000000000ULL;
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
				break;

			case 23:
				/*
				 * Optional and possibly repeated sync point.
				 * Injecting the timer IRQ may fail if the
				 * shinfo is invalid when the timer expires.
				 * If the timer has expired but the IRQ hasn't
				 * been delivered, rearm the timer and retry.
				 */
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_GET_ATTR, &tmr);

				/* Resume the guest if the timer is still pending. */
				if (tmr.u.timer.expires_ns)
					break;

				/* All done if the IRQ was delivered. */
				if (!evtchn_irq_expected)
					break;

				tmr.u.timer.expires_ns = rs->state_entry_time +
							 SHINFO_RACE_TIMEOUT * 1000000000ULL;
				vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &tmr);
				break;
			case 24:
				TEST_ASSERT(!evtchn_irq_expected,
					    "Expected event channel IRQ but it didn't happen");

				ret = pthread_cancel(thread);
				TEST_ASSERT(ret == 0, "pthread_cancel() failed: %s", strerror(ret));

				ret = pthread_join(thread, 0);
				TEST_ASSERT(ret == 0, "pthread_join() failed: %s", strerror(ret));
948 949
				goto done;

950 951 952 953
			case 0x20:
				TEST_ASSERT(evtchn_irq_expected, "Unexpected event channel IRQ");
				evtchn_irq_expected = false;
				break;
954
			}
955
			break;
956
		}
957 958 959 960 961 962 963 964
		case UCALL_DONE:
			goto done;
		default:
			TEST_FAIL("Unknown ucall 0x%lx.", uc.cmd);
		}
	}

 done:
965
	alarm(0);
966 967 968 969 970 971 972 973 974 975
	clock_gettime(CLOCK_REALTIME, &max_ts);

	/*
	 * Just a *really* basic check that things are being put in the
	 * right place. The actual calculations are much the same for
	 * Xen as they are for the KVM variants, so no need to check.
	 */
	struct pvclock_wall_clock *wc;
	struct pvclock_vcpu_time_info *ti, *ti2;

976 977 978
	wc = addr_gpa2hva(vm, SHINFO_REGION_GPA + 0xc00);
	ti = addr_gpa2hva(vm, SHINFO_REGION_GPA + 0x40 + 0x20);
	ti2 = addr_gpa2hva(vm, PVTIME_ADDR);
979

980 981 982 983 984 985 986 987 988 989
	if (verbose) {
		printf("Wall clock (v %d) %d.%09d\n", wc->version, wc->sec, wc->nsec);
		printf("Time info 1: v %u tsc %" PRIu64 " time %" PRIu64 " mul %u shift %u flags %x\n",
		       ti->version, ti->tsc_timestamp, ti->system_time, ti->tsc_to_system_mul,
		       ti->tsc_shift, ti->flags);
		printf("Time info 2: v %u tsc %" PRIu64 " time %" PRIu64 " mul %u shift %u flags %x\n",
		       ti2->version, ti2->tsc_timestamp, ti2->system_time, ti2->tsc_to_system_mul,
		       ti2->tsc_shift, ti2->flags);
	}

990 991
	vm_ts.tv_sec = wc->sec;
	vm_ts.tv_nsec = wc->nsec;
992
	TEST_ASSERT(wc->version && !(wc->version & 1),
993 994 995 996 997 998 999 1000 1001
		    "Bad wallclock version %x", wc->version);
	TEST_ASSERT(cmp_timespec(&min_ts, &vm_ts) <= 0, "VM time too old");
	TEST_ASSERT(cmp_timespec(&max_ts, &vm_ts) >= 0, "VM time too new");

	TEST_ASSERT(ti->version && !(ti->version & 1),
		    "Bad time_info version %x", ti->version);
	TEST_ASSERT(ti2->version && !(ti2->version & 1),
		    "Bad time_info version %x", ti->version);

1002 1003 1004 1005 1006 1007 1008 1009 1010
	if (do_runstate_tests) {
		/*
		 * Fetch runstate and check sanity. Strictly speaking in the
		 * general case we might not expect the numbers to be identical
		 * but in this case we know we aren't running the vCPU any more.
		 */
		struct kvm_xen_vcpu_attr rst = {
			.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA,
		};
1011
		vcpu_ioctl(vcpu, KVM_XEN_VCPU_GET_ATTR, &rst);
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021
		if (verbose) {
			printf("Runstate: %s(%d), entry %" PRIu64 " ns\n",
			       rs->state <= RUNSTATE_offline ? runstate_names[rs->state] : "unknown",
			       rs->state, rs->state_entry_time);
			for (int i = RUNSTATE_running; i <= RUNSTATE_offline; i++) {
				printf("State %s: %" PRIu64 " ns\n",
				       runstate_names[i], rs->time[i]);
			}
		}
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

		/*
		 * Exercise runstate info at all points across the page boundary, in
		 * 32-bit and 64-bit mode. In particular, test the case where it is
		 * configured in 32-bit mode and then switched to 64-bit mode while
		 * active, which takes it onto the second page.
		 */
		unsigned long runstate_addr;
		struct compat_vcpu_runstate_info *crs;
		for (runstate_addr = SHINFO_REGION_GPA + PAGE_SIZE + PAGE_SIZE - sizeof(*rs) - 4;
		     runstate_addr < SHINFO_REGION_GPA + PAGE_SIZE + PAGE_SIZE + 4; runstate_addr++) {

			rs = addr_gpa2hva(vm, runstate_addr);
			crs = (void *)rs;

			memset(rs, 0xa5, sizeof(*rs));

			/* Set to compatibility mode */
			lm.u.long_mode = 0;
			vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &lm);

			/* Set runstate to new address (kernel will write it) */
			struct kvm_xen_vcpu_attr st = {
				.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR,
				.u.gpa = runstate_addr,
			};
			vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &st);

			if (verbose)
				printf("Compatibility runstate at %08lx\n", runstate_addr);

			TEST_ASSERT(crs->state == rst.u.runstate.state, "Runstate mismatch");
			TEST_ASSERT(crs->state_entry_time == rst.u.runstate.state_entry_time,
				    "State entry time mismatch");
			TEST_ASSERT(crs->time[RUNSTATE_running] == rst.u.runstate.time_running,
				    "Running time mismatch");
			TEST_ASSERT(crs->time[RUNSTATE_runnable] == rst.u.runstate.time_runnable,
				    "Runnable time mismatch");
			TEST_ASSERT(crs->time[RUNSTATE_blocked] == rst.u.runstate.time_blocked,
				    "Blocked time mismatch");
			TEST_ASSERT(crs->time[RUNSTATE_offline] == rst.u.runstate.time_offline,
				    "Offline time mismatch");
			TEST_ASSERT(crs->time[RUNSTATE_offline + 1] == 0xa5a5a5a5a5a5a5a5ULL,
				    "Structure overrun");
			TEST_ASSERT(crs->state_entry_time == crs->time[0] +
				    crs->time[1] + crs->time[2] + crs->time[3],
				    "runstate times don't add up");


			/* Now switch to 64-bit mode */
			lm.u.long_mode = 1;
			vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &lm);

			memset(rs, 0xa5, sizeof(*rs));

			/* Don't change the address, just trigger a write */
			struct kvm_xen_vcpu_attr adj = {
				.type = KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST,
				.u.runstate.state = (uint64_t)-1
			};
			vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &adj);

			if (verbose)
				printf("64-bit runstate at %08lx\n", runstate_addr);

			TEST_ASSERT(rs->state == rst.u.runstate.state, "Runstate mismatch");
			TEST_ASSERT(rs->state_entry_time == rst.u.runstate.state_entry_time,
				    "State entry time mismatch");
			TEST_ASSERT(rs->time[RUNSTATE_running] == rst.u.runstate.time_running,
				    "Running time mismatch");
			TEST_ASSERT(rs->time[RUNSTATE_runnable] == rst.u.runstate.time_runnable,
				    "Runnable time mismatch");
			TEST_ASSERT(rs->time[RUNSTATE_blocked] == rst.u.runstate.time_blocked,
				    "Blocked time mismatch");
			TEST_ASSERT(rs->time[RUNSTATE_offline] == rst.u.runstate.time_offline,
				    "Offline time mismatch");
			TEST_ASSERT(rs->time[RUNSTATE_offline + 1] == 0xa5a5a5a5a5a5a5a5ULL,
				    "Structure overrun");

			TEST_ASSERT(rs->state_entry_time == rs->time[0] +
				    rs->time[1] + rs->time[2] + rs->time[3],
				    "runstate times don't add up");
		}
1105
	}
1106

1107 1108 1109
	kvm_vm_free(vm);
	return 0;
}