hyperv.c 62.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * KVM Microsoft Hyper-V emulation
 *
 * derived from arch/x86/kvm/x86.c
 *
 * Copyright (C) 2006 Qumranet, Inc.
 * Copyright (C) 2008 Qumranet, Inc.
 * Copyright IBM Corporation, 2008
 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
 * Copyright (C) 2015 Andrey Smetanin <asmetanin@virtuozzo.com>
 *
 * Authors:
 *   Avi Kivity   <avi@qumranet.com>
 *   Yaniv Kamay  <yaniv@qumranet.com>
 *   Amit Shah    <amit.shah@qumranet.com>
 *   Ben-Ami Yassour <benami@il.ibm.com>
 *   Andrey Smetanin <asmetanin@virtuozzo.com>
 */

#include "x86.h"
#include "lapic.h"
23
#include "ioapic.h"
24
#include "cpuid.h"
25
#include "hyperv.h"
26
#include "xen.h"
27

28
#include <linux/cpu.h>
29
#include <linux/kvm_host.h>
30
#include <linux/highmem.h>
31
#include <linux/sched/cputime.h>
32
#include <linux/eventfd.h>
33

34
#include <asm/apicdef.h>
35 36 37
#include <trace/events/kvm.h>

#include "trace.h"
38
#include "irq.h"
39
#include "fpu.h"
40

41 42 43
/* "Hv#1" signature */
#define HYPERV_CPUID_SIGNATURE_EAX 0x31237648

44 45
#define KVM_HV_MAX_SPARSE_VCPU_SET_BITS DIV_ROUND_UP(KVM_MAX_VCPUS, 64)

46 47 48
static void stimer_mark_pending(struct kvm_vcpu_hv_stimer *stimer,
				bool vcpu_kick);

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
static inline u64 synic_read_sint(struct kvm_vcpu_hv_synic *synic, int sint)
{
	return atomic64_read(&synic->sint[sint]);
}

static inline int synic_get_sint_vector(u64 sint_value)
{
	if (sint_value & HV_SYNIC_SINT_MASKED)
		return -1;
	return sint_value & HV_SYNIC_SINT_VECTOR_MASK;
}

static bool synic_has_vector_connected(struct kvm_vcpu_hv_synic *synic,
				      int vector)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
		if (synic_get_sint_vector(synic_read_sint(synic, i)) == vector)
			return true;
	}
	return false;
}

static bool synic_has_vector_auto_eoi(struct kvm_vcpu_hv_synic *synic,
				     int vector)
{
	int i;
	u64 sint_value;

	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
		sint_value = synic_read_sint(synic, i);
		if (synic_get_sint_vector(sint_value) == vector &&
		    sint_value & HV_SYNIC_SINT_AUTO_EOI)
			return true;
	}
	return false;
}

88 89 90
static void synic_update_vector(struct kvm_vcpu_hv_synic *synic,
				int vector)
{
91 92 93
	if (vector < HV_SYNIC_FIRST_VALID_VECTOR)
		return;

94 95 96 97 98 99 100 101 102 103 104
	if (synic_has_vector_connected(synic, vector))
		__set_bit(vector, synic->vec_bitmap);
	else
		__clear_bit(vector, synic->vec_bitmap);

	if (synic_has_vector_auto_eoi(synic, vector))
		__set_bit(vector, synic->auto_eoi_bitmap);
	else
		__clear_bit(vector, synic->auto_eoi_bitmap);
}

105 106
static int synic_set_sint(struct kvm_vcpu_hv_synic *synic, int sint,
			  u64 data, bool host)
107
{
108
	int vector, old_vector;
109
	bool masked;
110 111

	vector = data & HV_SYNIC_SINT_VECTOR_MASK;
112 113 114 115 116 117 118 119
	masked = data & HV_SYNIC_SINT_MASKED;

	/*
	 * Valid vectors are 16-255, however, nested Hyper-V attempts to write
	 * default '0x10000' value on boot and this should not #GP. We need to
	 * allow zero-initing the register from host as well.
	 */
	if (vector < HV_SYNIC_FIRST_VALID_VECTOR && !host && !masked)
120 121 122 123 124 125 126
		return 1;
	/*
	 * Guest may configure multiple SINTs to use the same vector, so
	 * we maintain a bitmap of vectors handled by synic, and a
	 * bitmap of vectors with auto-eoi behavior.  The bitmaps are
	 * updated here, and atomically queried on fast paths.
	 */
127
	old_vector = synic_read_sint(synic, sint) & HV_SYNIC_SINT_VECTOR_MASK;
128 129 130

	atomic64_set(&synic->sint[sint], data);

131
	synic_update_vector(synic, old_vector);
132

133
	synic_update_vector(synic, vector);
134 135

	/* Load SynIC vectors into EOI exit bitmap */
136
	kvm_make_request(KVM_REQ_SCAN_IOAPIC, hv_synic_to_vcpu(synic));
137 138 139
	return 0;
}

140 141 142 143 144
static struct kvm_vcpu *get_vcpu_by_vpidx(struct kvm *kvm, u32 vpidx)
{
	struct kvm_vcpu *vcpu = NULL;
	int i;

145 146 147 148
	if (vpidx >= KVM_MAX_VCPUS)
		return NULL;

	vcpu = kvm_get_vcpu(kvm, vpidx);
149
	if (vcpu && kvm_hv_get_vpindex(vcpu) == vpidx)
150 151
		return vcpu;
	kvm_for_each_vcpu(i, vcpu, kvm)
152
		if (kvm_hv_get_vpindex(vcpu) == vpidx)
153 154 155 156 157
			return vcpu;
	return NULL;
}

static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)
158 159 160 161
{
	struct kvm_vcpu *vcpu;
	struct kvm_vcpu_hv_synic *synic;

162
	vcpu = get_vcpu_by_vpidx(kvm, vpidx);
163
	if (!vcpu || !to_hv_vcpu(vcpu))
164
		return NULL;
165
	synic = to_hv_synic(vcpu);
166 167 168 169 170 171
	return (synic->active) ? synic : NULL;
}

static void kvm_hv_notify_acked_sint(struct kvm_vcpu *vcpu, u32 sint)
{
	struct kvm *kvm = vcpu->kvm;
172
	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
173
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
A
Andrey Smetanin 已提交
174
	struct kvm_vcpu_hv_stimer *stimer;
175
	int gsi, idx;
176

177
	trace_kvm_hv_notify_acked_sint(vcpu->vcpu_id, sint);
178

A
Andrey Smetanin 已提交
179 180 181
	/* Try to deliver pending Hyper-V SynIC timers messages */
	for (idx = 0; idx < ARRAY_SIZE(hv_vcpu->stimer); idx++) {
		stimer = &hv_vcpu->stimer[idx];
182
		if (stimer->msg_pending && stimer->config.enable &&
183
		    !stimer->config.direct_mode &&
184 185
		    stimer->config.sintx == sint)
			stimer_mark_pending(stimer, false);
A
Andrey Smetanin 已提交
186 187
	}

188
	idx = srcu_read_lock(&kvm->irq_srcu);
A
Andrey Smetanin 已提交
189
	gsi = atomic_read(&synic->sint_to_gsi[sint]);
190 191 192 193 194
	if (gsi != -1)
		kvm_notify_acked_gsi(kvm, gsi);
	srcu_read_unlock(&kvm->irq_srcu, idx);
}

A
Andrey Smetanin 已提交
195 196
static void synic_exit(struct kvm_vcpu_hv_synic *synic, u32 msr)
{
197
	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
198
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
A
Andrey Smetanin 已提交
199 200 201 202 203 204 205 206 207 208

	hv_vcpu->exit.type = KVM_EXIT_HYPERV_SYNIC;
	hv_vcpu->exit.u.synic.msr = msr;
	hv_vcpu->exit.u.synic.control = synic->control;
	hv_vcpu->exit.u.synic.evt_page = synic->evt_page;
	hv_vcpu->exit.u.synic.msg_page = synic->msg_page;

	kvm_make_request(KVM_REQ_HV_EXIT, vcpu);
}

209 210 211
static int synic_set_msr(struct kvm_vcpu_hv_synic *synic,
			 u32 msr, u64 data, bool host)
{
212
	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
213 214
	int ret;

215
	if (!synic->active && !host)
216 217
		return 1;

218 219
	trace_kvm_hv_synic_set_msr(vcpu->vcpu_id, msr, data, host);

220 221 222 223
	ret = 0;
	switch (msr) {
	case HV_X64_MSR_SCONTROL:
		synic->control = data;
A
Andrey Smetanin 已提交
224 225
		if (!host)
			synic_exit(synic, msr);
226 227 228 229 230 231 232 233 234
		break;
	case HV_X64_MSR_SVERSION:
		if (!host) {
			ret = 1;
			break;
		}
		synic->version = data;
		break;
	case HV_X64_MSR_SIEFP:
235 236
		if ((data & HV_SYNIC_SIEFP_ENABLE) && !host &&
		    !synic->dont_zero_synic_pages)
237 238 239 240 241 242
			if (kvm_clear_guest(vcpu->kvm,
					    data & PAGE_MASK, PAGE_SIZE)) {
				ret = 1;
				break;
			}
		synic->evt_page = data;
A
Andrey Smetanin 已提交
243 244
		if (!host)
			synic_exit(synic, msr);
245 246
		break;
	case HV_X64_MSR_SIMP:
247 248
		if ((data & HV_SYNIC_SIMP_ENABLE) && !host &&
		    !synic->dont_zero_synic_pages)
249 250 251 252 253 254
			if (kvm_clear_guest(vcpu->kvm,
					    data & PAGE_MASK, PAGE_SIZE)) {
				ret = 1;
				break;
			}
		synic->msg_page = data;
A
Andrey Smetanin 已提交
255 256
		if (!host)
			synic_exit(synic, msr);
257 258 259 260 261 262 263 264 265
		break;
	case HV_X64_MSR_EOM: {
		int i;

		for (i = 0; i < ARRAY_SIZE(synic->sint); i++)
			kvm_hv_notify_acked_sint(vcpu, i);
		break;
	}
	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
266
		ret = synic_set_sint(synic, msr - HV_X64_MSR_SINT0, data, host);
267 268 269 270 271 272 273 274
		break;
	default:
		ret = 1;
		break;
	}
	return ret;
}

275 276
static bool kvm_hv_is_syndbg_enabled(struct kvm_vcpu *vcpu)
{
277
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
278

279 280
	return hv_vcpu->cpuid_cache.syndbg_cap_eax &
		HV_X64_SYNDBG_CAP_ALLOW_KERNEL_DEBUGGING;
281 282 283 284
}

static int kvm_hv_syndbg_complete_userspace(struct kvm_vcpu *vcpu)
{
285
	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
286 287 288 289 290 291 292 293 294

	if (vcpu->run->hyperv.u.syndbg.msr == HV_X64_MSR_SYNDBG_CONTROL)
		hv->hv_syndbg.control.status =
			vcpu->run->hyperv.u.syndbg.status;
	return 1;
}

static void syndbg_exit(struct kvm_vcpu *vcpu, u32 msr)
{
295
	struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
296
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311

	hv_vcpu->exit.type = KVM_EXIT_HYPERV_SYNDBG;
	hv_vcpu->exit.u.syndbg.msr = msr;
	hv_vcpu->exit.u.syndbg.control = syndbg->control.control;
	hv_vcpu->exit.u.syndbg.send_page = syndbg->control.send_page;
	hv_vcpu->exit.u.syndbg.recv_page = syndbg->control.recv_page;
	hv_vcpu->exit.u.syndbg.pending_page = syndbg->control.pending_page;
	vcpu->arch.complete_userspace_io =
			kvm_hv_syndbg_complete_userspace;

	kvm_make_request(KVM_REQ_HV_EXIT, vcpu);
}

static int syndbg_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
{
312
	struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
313 314 315 316 317

	if (!kvm_hv_is_syndbg_enabled(vcpu) && !host)
		return 1;

	trace_kvm_hv_syndbg_set_msr(vcpu->vcpu_id,
318
				    to_hv_vcpu(vcpu)->vp_index, msr, data);
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	switch (msr) {
	case HV_X64_MSR_SYNDBG_CONTROL:
		syndbg->control.control = data;
		if (!host)
			syndbg_exit(vcpu, msr);
		break;
	case HV_X64_MSR_SYNDBG_STATUS:
		syndbg->control.status = data;
		break;
	case HV_X64_MSR_SYNDBG_SEND_BUFFER:
		syndbg->control.send_page = data;
		break;
	case HV_X64_MSR_SYNDBG_RECV_BUFFER:
		syndbg->control.recv_page = data;
		break;
	case HV_X64_MSR_SYNDBG_PENDING_BUFFER:
		syndbg->control.pending_page = data;
		if (!host)
			syndbg_exit(vcpu, msr);
		break;
	case HV_X64_MSR_SYNDBG_OPTIONS:
		syndbg->options = data;
		break;
	default:
		break;
	}

	return 0;
}

static int syndbg_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
{
351
	struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
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

	if (!kvm_hv_is_syndbg_enabled(vcpu) && !host)
		return 1;

	switch (msr) {
	case HV_X64_MSR_SYNDBG_CONTROL:
		*pdata = syndbg->control.control;
		break;
	case HV_X64_MSR_SYNDBG_STATUS:
		*pdata = syndbg->control.status;
		break;
	case HV_X64_MSR_SYNDBG_SEND_BUFFER:
		*pdata = syndbg->control.send_page;
		break;
	case HV_X64_MSR_SYNDBG_RECV_BUFFER:
		*pdata = syndbg->control.recv_page;
		break;
	case HV_X64_MSR_SYNDBG_PENDING_BUFFER:
		*pdata = syndbg->control.pending_page;
		break;
	case HV_X64_MSR_SYNDBG_OPTIONS:
		*pdata = syndbg->options;
		break;
	default:
		break;
	}

379
	trace_kvm_hv_syndbg_get_msr(vcpu->vcpu_id, kvm_hv_get_vpindex(vcpu), msr, *pdata);
380 381 382 383

	return 0;
}

384 385
static int synic_get_msr(struct kvm_vcpu_hv_synic *synic, u32 msr, u64 *pdata,
			 bool host)
386 387 388
{
	int ret;

389
	if (!synic->active && !host)
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
		return 1;

	ret = 0;
	switch (msr) {
	case HV_X64_MSR_SCONTROL:
		*pdata = synic->control;
		break;
	case HV_X64_MSR_SVERSION:
		*pdata = synic->version;
		break;
	case HV_X64_MSR_SIEFP:
		*pdata = synic->evt_page;
		break;
	case HV_X64_MSR_SIMP:
		*pdata = synic->msg_page;
		break;
	case HV_X64_MSR_EOM:
		*pdata = 0;
		break;
	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
		*pdata = atomic64_read(&synic->sint[msr - HV_X64_MSR_SINT0]);
		break;
	default:
		ret = 1;
		break;
	}
	return ret;
}

419
static int synic_set_irq(struct kvm_vcpu_hv_synic *synic, u32 sint)
420
{
421
	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
422 423 424 425 426 427 428 429 430 431 432
	struct kvm_lapic_irq irq;
	int ret, vector;

	if (sint >= ARRAY_SIZE(synic->sint))
		return -EINVAL;

	vector = synic_get_sint_vector(synic_read_sint(synic, sint));
	if (vector < 0)
		return -ENOENT;

	memset(&irq, 0, sizeof(irq));
433
	irq.shorthand = APIC_DEST_SELF;
434 435 436 437 438
	irq.dest_mode = APIC_DEST_PHYSICAL;
	irq.delivery_mode = APIC_DM_FIXED;
	irq.vector = vector;
	irq.level = 1;

439
	ret = kvm_irq_delivery_to_apic(vcpu->kvm, vcpu->arch.apic, &irq, NULL);
440
	trace_kvm_hv_synic_set_irq(vcpu->vcpu_id, sint, irq.vector, ret);
441 442 443
	return ret;
}

444
int kvm_hv_synic_set_irq(struct kvm *kvm, u32 vpidx, u32 sint)
445 446 447
{
	struct kvm_vcpu_hv_synic *synic;

448
	synic = synic_get(kvm, vpidx);
449 450 451 452 453 454 455 456
	if (!synic)
		return -EINVAL;

	return synic_set_irq(synic, sint);
}

void kvm_hv_synic_send_eoi(struct kvm_vcpu *vcpu, int vector)
{
457
	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
458 459
	int i;

460
	trace_kvm_hv_synic_send_eoi(vcpu->vcpu_id, vector);
461 462 463 464 465 466

	for (i = 0; i < ARRAY_SIZE(synic->sint); i++)
		if (synic_get_sint_vector(synic_read_sint(synic, i)) == vector)
			kvm_hv_notify_acked_sint(vcpu, i);
}

467
static int kvm_hv_set_sint_gsi(struct kvm *kvm, u32 vpidx, u32 sint, int gsi)
468 469 470
{
	struct kvm_vcpu_hv_synic *synic;

471
	synic = synic_get(kvm, vpidx);
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
	if (!synic)
		return -EINVAL;

	if (sint >= ARRAY_SIZE(synic->sint_to_gsi))
		return -EINVAL;

	atomic_set(&synic->sint_to_gsi[sint], gsi);
	return 0;
}

void kvm_hv_irq_routing_update(struct kvm *kvm)
{
	struct kvm_irq_routing_table *irq_rt;
	struct kvm_kernel_irq_routing_entry *e;
	u32 gsi;

	irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu,
					lockdep_is_held(&kvm->irq_lock));

	for (gsi = 0; gsi < irq_rt->nr_rt_entries; gsi++) {
		hlist_for_each_entry(e, &irq_rt->map[gsi], link) {
			if (e->type == KVM_IRQ_ROUTING_HV_SINT)
				kvm_hv_set_sint_gsi(kvm, e->hv_sint.vcpu,
						    e->hv_sint.sint, gsi);
		}
	}
}

static void synic_init(struct kvm_vcpu_hv_synic *synic)
{
	int i;

	memset(synic, 0, sizeof(*synic));
	synic->version = HV_SYNIC_VERSION_1;
	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
		atomic64_set(&synic->sint[i], HV_SYNIC_SINT_MASKED);
		atomic_set(&synic->sint_to_gsi[i], -1);
	}
}

512 513
static u64 get_time_ref_counter(struct kvm *kvm)
{
514
	struct kvm_hv *hv = to_kvm_hv(kvm);
P
Paolo Bonzini 已提交
515 516 517 518
	struct kvm_vcpu *vcpu;
	u64 tsc;

	/*
519 520
	 * Fall back to get_kvmclock_ns() when TSC page hasn't been set up,
	 * is broken, disabled or being updated.
P
Paolo Bonzini 已提交
521
	 */
522
	if (hv->hv_tsc_page_status != HV_TSC_PAGE_SET)
P
Paolo Bonzini 已提交
523 524 525 526 527 528
		return div_u64(get_kvmclock_ns(kvm), 100);

	vcpu = kvm_get_vcpu(kvm, 0);
	tsc = kvm_read_l1_tsc(vcpu, rdtsc());
	return mul_u64_u64_shr(tsc, hv->tsc_ref.tsc_scale, 64)
		+ hv->tsc_ref.tsc_offset;
529 530
}

531
static void stimer_mark_pending(struct kvm_vcpu_hv_stimer *stimer,
A
Andrey Smetanin 已提交
532 533
				bool vcpu_kick)
{
534
	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
A
Andrey Smetanin 已提交
535 536

	set_bit(stimer->index,
537
		to_hv_vcpu(vcpu)->stimer_pending_bitmap);
A
Andrey Smetanin 已提交
538 539 540 541 542 543 544
	kvm_make_request(KVM_REQ_HV_STIMER, vcpu);
	if (vcpu_kick)
		kvm_vcpu_kick(vcpu);
}

static void stimer_cleanup(struct kvm_vcpu_hv_stimer *stimer)
{
545
	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
A
Andrey Smetanin 已提交
546

547
	trace_kvm_hv_stimer_cleanup(hv_stimer_to_vcpu(stimer)->vcpu_id,
548 549
				    stimer->index);

550
	hrtimer_cancel(&stimer->timer);
A
Andrey Smetanin 已提交
551
	clear_bit(stimer->index,
552
		  to_hv_vcpu(vcpu)->stimer_pending_bitmap);
A
Andrey Smetanin 已提交
553
	stimer->msg_pending = false;
554
	stimer->exp_time = 0;
A
Andrey Smetanin 已提交
555 556 557 558 559 560 561
}

static enum hrtimer_restart stimer_timer_callback(struct hrtimer *timer)
{
	struct kvm_vcpu_hv_stimer *stimer;

	stimer = container_of(timer, struct kvm_vcpu_hv_stimer, timer);
562
	trace_kvm_hv_stimer_callback(hv_stimer_to_vcpu(stimer)->vcpu_id,
563
				     stimer->index);
564
	stimer_mark_pending(stimer, true);
A
Andrey Smetanin 已提交
565 566 567 568

	return HRTIMER_NORESTART;
}

569 570 571 572 573
/*
 * stimer_start() assumptions:
 * a) stimer->count is not equal to 0
 * b) stimer->config has HV_STIMER_ENABLE flag
 */
A
Andrey Smetanin 已提交
574 575 576 577 578
static int stimer_start(struct kvm_vcpu_hv_stimer *stimer)
{
	u64 time_now;
	ktime_t ktime_now;

579
	time_now = get_time_ref_counter(hv_stimer_to_vcpu(stimer)->kvm);
A
Andrey Smetanin 已提交
580 581
	ktime_now = ktime_get();

582
	if (stimer->config.periodic) {
583 584 585 586 587 588 589 590 591 592 593
		if (stimer->exp_time) {
			if (time_now >= stimer->exp_time) {
				u64 remainder;

				div64_u64_rem(time_now - stimer->exp_time,
					      stimer->count, &remainder);
				stimer->exp_time =
					time_now + (stimer->count - remainder);
			}
		} else
			stimer->exp_time = time_now + stimer->count;
A
Andrey Smetanin 已提交
594

595
		trace_kvm_hv_stimer_start_periodic(
596
					hv_stimer_to_vcpu(stimer)->vcpu_id,
597 598 599
					stimer->index,
					time_now, stimer->exp_time);

A
Andrey Smetanin 已提交
600
		hrtimer_start(&stimer->timer,
601 602
			      ktime_add_ns(ktime_now,
					   100 * (stimer->exp_time - time_now)),
A
Andrey Smetanin 已提交
603 604 605 606 607 608 609 610 611 612 613
			      HRTIMER_MODE_ABS);
		return 0;
	}
	stimer->exp_time = stimer->count;
	if (time_now >= stimer->count) {
		/*
		 * Expire timer according to Hypervisor Top-Level Functional
		 * specification v4(15.3.1):
		 * "If a one shot is enabled and the specified count is in
		 * the past, it will expire immediately."
		 */
614
		stimer_mark_pending(stimer, false);
A
Andrey Smetanin 已提交
615 616 617
		return 0;
	}

618
	trace_kvm_hv_stimer_start_one_shot(hv_stimer_to_vcpu(stimer)->vcpu_id,
619 620 621
					   stimer->index,
					   time_now, stimer->count);

A
Andrey Smetanin 已提交
622 623 624 625 626 627 628 629 630
	hrtimer_start(&stimer->timer,
		      ktime_add_ns(ktime_now, 100 * (stimer->count - time_now)),
		      HRTIMER_MODE_ABS);
	return 0;
}

static int stimer_set_config(struct kvm_vcpu_hv_stimer *stimer, u64 config,
			     bool host)
{
631 632
	union hv_stimer_config new_config = {.as_uint64 = config},
		old_config = {.as_uint64 = stimer->config.as_uint64};
633
	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
634
	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
635 636 637

	if (!synic->active && !host)
		return 1;
638

639
	trace_kvm_hv_stimer_set_config(hv_stimer_to_vcpu(stimer)->vcpu_id,
640 641
				       stimer->index, config, host);

642
	stimer_cleanup(stimer);
643 644
	if (old_config.enable &&
	    !new_config.direct_mode && new_config.sintx == 0)
645 646
		new_config.enable = 0;
	stimer->config.as_uint64 = new_config.as_uint64;
647

648 649 650
	if (stimer->config.enable)
		stimer_mark_pending(stimer, false);

A
Andrey Smetanin 已提交
651 652 653 654 655 656
	return 0;
}

static int stimer_set_count(struct kvm_vcpu_hv_stimer *stimer, u64 count,
			    bool host)
{
657
	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
658
	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
659 660 661 662

	if (!synic->active && !host)
		return 1;

663
	trace_kvm_hv_stimer_set_count(hv_stimer_to_vcpu(stimer)->vcpu_id,
664 665
				      stimer->index, count, host);

A
Andrey Smetanin 已提交
666
	stimer_cleanup(stimer);
667
	stimer->count = count;
A
Andrey Smetanin 已提交
668
	if (stimer->count == 0)
669 670 671
		stimer->config.enable = 0;
	else if (stimer->config.auto_enable)
		stimer->config.enable = 1;
672 673 674 675

	if (stimer->config.enable)
		stimer_mark_pending(stimer, false);

A
Andrey Smetanin 已提交
676 677 678 679 680
	return 0;
}

static int stimer_get_config(struct kvm_vcpu_hv_stimer *stimer, u64 *pconfig)
{
681
	*pconfig = stimer->config.as_uint64;
A
Andrey Smetanin 已提交
682 683 684 685 686 687 688 689 690 691
	return 0;
}

static int stimer_get_count(struct kvm_vcpu_hv_stimer *stimer, u64 *pcount)
{
	*pcount = stimer->count;
	return 0;
}

static int synic_deliver_msg(struct kvm_vcpu_hv_synic *synic, u32 sint,
692
			     struct hv_message *src_msg, bool no_retry)
A
Andrey Smetanin 已提交
693
{
694
	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
695 696 697
	int msg_off = offsetof(struct hv_message_page, sint_message[sint]);
	gfn_t msg_page_gfn;
	struct hv_message_header hv_hdr;
A
Andrey Smetanin 已提交
698 699 700 701 702
	int r;

	if (!(synic->msg_page & HV_SYNIC_SIMP_ENABLE))
		return -ENOENT;

703
	msg_page_gfn = synic->msg_page >> PAGE_SHIFT;
A
Andrey Smetanin 已提交
704

705 706 707 708 709 710 711 712 713 714 715 716 717 718
	/*
	 * Strictly following the spec-mandated ordering would assume setting
	 * .msg_pending before checking .message_type.  However, this function
	 * is only called in vcpu context so the entire update is atomic from
	 * guest POV and thus the exact order here doesn't matter.
	 */
	r = kvm_vcpu_read_guest_page(vcpu, msg_page_gfn, &hv_hdr.message_type,
				     msg_off + offsetof(struct hv_message,
							header.message_type),
				     sizeof(hv_hdr.message_type));
	if (r < 0)
		return r;

	if (hv_hdr.message_type != HVMSG_NONE) {
719 720 721
		if (no_retry)
			return 0;

722 723 724 725 726 727 728 729 730 731
		hv_hdr.message_flags.msg_pending = 1;
		r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn,
					      &hv_hdr.message_flags,
					      msg_off +
					      offsetof(struct hv_message,
						       header.message_flags),
					      sizeof(hv_hdr.message_flags));
		if (r < 0)
			return r;
		return -EAGAIN;
A
Andrey Smetanin 已提交
732
	}
733 734 735 736 737 738 739 740 741 742 743 744 745

	r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn, src_msg, msg_off,
				      sizeof(src_msg->header) +
				      src_msg->header.payload_size);
	if (r < 0)
		return r;

	r = synic_set_irq(synic, sint);
	if (r < 0)
		return r;
	if (r == 0)
		return -EFAULT;
	return 0;
A
Andrey Smetanin 已提交
746 747
}

748
static int stimer_send_msg(struct kvm_vcpu_hv_stimer *stimer)
A
Andrey Smetanin 已提交
749
{
750
	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
A
Andrey Smetanin 已提交
751 752 753 754
	struct hv_message *msg = &stimer->msg;
	struct hv_timer_message_payload *payload =
			(struct hv_timer_message_payload *)&msg->u.payload;

755 756 757 758
	/*
	 * To avoid piling up periodic ticks, don't retry message
	 * delivery for them (within "lazy" lost ticks policy).
	 */
759
	bool no_retry = stimer->config.periodic;
760

A
Andrey Smetanin 已提交
761 762
	payload->expiration_time = stimer->exp_time;
	payload->delivery_time = get_time_ref_counter(vcpu->kvm);
763
	return synic_deliver_msg(to_hv_synic(vcpu),
764
				 stimer->config.sintx, msg,
765
				 no_retry);
A
Andrey Smetanin 已提交
766 767
}

768 769
static int stimer_notify_direct(struct kvm_vcpu_hv_stimer *stimer)
{
770
	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
771 772 773 774 775
	struct kvm_lapic_irq irq = {
		.delivery_mode = APIC_DM_FIXED,
		.vector = stimer->config.apic_vector
	};

776 777 778
	if (lapic_in_kernel(vcpu))
		return !kvm_apic_set_irq(vcpu, &irq, NULL);
	return 0;
779 780
}

A
Andrey Smetanin 已提交
781 782
static void stimer_expiration(struct kvm_vcpu_hv_stimer *stimer)
{
783
	int r, direct = stimer->config.direct_mode;
784

785
	stimer->msg_pending = true;
786 787 788 789
	if (!direct)
		r = stimer_send_msg(stimer);
	else
		r = stimer_notify_direct(stimer);
790
	trace_kvm_hv_stimer_expiration(hv_stimer_to_vcpu(stimer)->vcpu_id,
791
				       stimer->index, direct, r);
792
	if (!r) {
793
		stimer->msg_pending = false;
794 795
		if (!(stimer->config.periodic))
			stimer->config.enable = 0;
796
	}
A
Andrey Smetanin 已提交
797 798 799 800
}

void kvm_hv_process_stimers(struct kvm_vcpu *vcpu)
{
801
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
A
Andrey Smetanin 已提交
802
	struct kvm_vcpu_hv_stimer *stimer;
803
	u64 time_now, exp_time;
A
Andrey Smetanin 已提交
804 805
	int i;

806 807 808
	if (!hv_vcpu)
		return;

A
Andrey Smetanin 已提交
809 810 811
	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
		if (test_and_clear_bit(i, hv_vcpu->stimer_pending_bitmap)) {
			stimer = &hv_vcpu->stimer[i];
812
			if (stimer->config.enable) {
813 814 815 816 817 818 819 820
				exp_time = stimer->exp_time;

				if (exp_time) {
					time_now =
						get_time_ref_counter(vcpu->kvm);
					if (time_now >= exp_time)
						stimer_expiration(stimer);
				}
821

822
				if ((stimer->config.enable) &&
823 824 825 826
				    stimer->count) {
					if (!stimer->msg_pending)
						stimer_start(stimer);
				} else
827
					stimer_cleanup(stimer);
A
Andrey Smetanin 已提交
828 829 830 831 832 833
			}
		}
}

void kvm_hv_vcpu_uninit(struct kvm_vcpu *vcpu)
{
834
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
A
Andrey Smetanin 已提交
835 836
	int i;

837 838 839
	if (!hv_vcpu)
		return;

A
Andrey Smetanin 已提交
840 841
	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
		stimer_cleanup(&hv_vcpu->stimer[i]);
842 843 844

	kfree(hv_vcpu);
	vcpu->arch.hyperv = NULL;
A
Andrey Smetanin 已提交
845 846
}

847 848
bool kvm_hv_assist_page_enabled(struct kvm_vcpu *vcpu)
{
849 850
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);

851 852 853
	if (!hv_vcpu)
		return false;

854
	if (!(hv_vcpu->hv_vapic & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE))
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
		return false;
	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
}
EXPORT_SYMBOL_GPL(kvm_hv_assist_page_enabled);

bool kvm_hv_get_assist_page(struct kvm_vcpu *vcpu,
			    struct hv_vp_assist_page *assist_page)
{
	if (!kvm_hv_assist_page_enabled(vcpu))
		return false;
	return !kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data,
				      assist_page, sizeof(*assist_page));
}
EXPORT_SYMBOL_GPL(kvm_hv_get_assist_page);

A
Andrey Smetanin 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
static void stimer_prepare_msg(struct kvm_vcpu_hv_stimer *stimer)
{
	struct hv_message *msg = &stimer->msg;
	struct hv_timer_message_payload *payload =
			(struct hv_timer_message_payload *)&msg->u.payload;

	memset(&msg->header, 0, sizeof(msg->header));
	msg->header.message_type = HVMSG_TIMER_EXPIRED;
	msg->header.payload_size = sizeof(*payload);

	payload->timer_index = stimer->index;
	payload->expiration_time = 0;
	payload->delivery_time = 0;
}

static void stimer_init(struct kvm_vcpu_hv_stimer *stimer, int timer_index)
{
	memset(stimer, 0, sizeof(*stimer));
	stimer->index = timer_index;
	hrtimer_init(&stimer->timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
	stimer->timer.function = stimer_timer_callback;
	stimer_prepare_msg(stimer);
}

894
static int kvm_hv_vcpu_init(struct kvm_vcpu *vcpu)
895
{
896
	struct kvm_vcpu_hv *hv_vcpu;
A
Andrey Smetanin 已提交
897 898
	int i;

899 900 901 902 903 904 905
	hv_vcpu = kzalloc(sizeof(struct kvm_vcpu_hv), GFP_KERNEL_ACCOUNT);
	if (!hv_vcpu)
		return -ENOMEM;

	vcpu->arch.hyperv = hv_vcpu;
	hv_vcpu->vcpu = vcpu;

A
Andrey Smetanin 已提交
906 907 908 909 910
	synic_init(&hv_vcpu->synic);

	bitmap_zero(hv_vcpu->stimer_pending_bitmap, HV_SYNIC_STIMER_COUNT);
	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
		stimer_init(&hv_vcpu->stimer[i], i);
911

912 913
	hv_vcpu->vp_index = kvm_vcpu_get_idx(vcpu);

914
	return 0;
915 916
}

917
int kvm_hv_activate_synic(struct kvm_vcpu *vcpu, bool dont_zero_synic_pages)
918
{
919 920
	struct kvm_vcpu_hv_synic *synic;
	int r;
921

922 923 924 925 926
	if (!to_hv_vcpu(vcpu)) {
		r = kvm_hv_vcpu_init(vcpu);
		if (r)
			return r;
	}
927

928
	synic = to_hv_synic(vcpu);
929

930 931
	/*
	 * Hyper-V SynIC auto EOI SINT's are
932 933
	 * not compatible with APICV, so request
	 * to deactivate APICV permanently.
934
	 */
935
	kvm_request_apicv_update(vcpu->kvm, false, APICV_INHIBIT_REASON_HYPERV);
936 937
	synic->active = true;
	synic->dont_zero_synic_pages = dont_zero_synic_pages;
938
	synic->control = HV_SYNIC_CONTROL_ENABLE;
939 940 941
	return 0;
}

942 943 944 945 946 947 948 949 950
static bool kvm_hv_msr_partition_wide(u32 msr)
{
	bool r = false;

	switch (msr) {
	case HV_X64_MSR_GUEST_OS_ID:
	case HV_X64_MSR_HYPERCALL:
	case HV_X64_MSR_REFERENCE_TSC:
	case HV_X64_MSR_TIME_REF_COUNT:
951 952
	case HV_X64_MSR_CRASH_CTL:
	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
953
	case HV_X64_MSR_RESET:
954 955 956
	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
	case HV_X64_MSR_TSC_EMULATION_CONTROL:
	case HV_X64_MSR_TSC_EMULATION_STATUS:
957 958
	case HV_X64_MSR_SYNDBG_OPTIONS:
	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
959 960 961 962 963 964 965
		r = true;
		break;
	}

	return r;
}

966
static int kvm_hv_msr_get_crash_data(struct kvm *kvm, u32 index, u64 *pdata)
967
{
968
	struct kvm_hv *hv = to_kvm_hv(kvm);
969
	size_t size = ARRAY_SIZE(hv->hv_crash_param);
970

971
	if (WARN_ON_ONCE(index >= size))
972 973
		return -EINVAL;

974
	*pdata = hv->hv_crash_param[array_index_nospec(index, size)];
975 976 977
	return 0;
}

978
static int kvm_hv_msr_get_crash_ctl(struct kvm *kvm, u64 *pdata)
979
{
980
	struct kvm_hv *hv = to_kvm_hv(kvm);
981 982 983 984 985

	*pdata = hv->hv_crash_ctl;
	return 0;
}

986
static int kvm_hv_msr_set_crash_ctl(struct kvm *kvm, u64 data)
987
{
988
	struct kvm_hv *hv = to_kvm_hv(kvm);
989

990
	hv->hv_crash_ctl = data & HV_CRASH_CTL_CRASH_NOTIFY;
991 992 993 994

	return 0;
}

995
static int kvm_hv_msr_set_crash_data(struct kvm *kvm, u32 index, u64 data)
996
{
997
	struct kvm_hv *hv = to_kvm_hv(kvm);
998
	size_t size = ARRAY_SIZE(hv->hv_crash_param);
999

1000
	if (WARN_ON_ONCE(index >= size))
1001 1002
		return -EINVAL;

1003
	hv->hv_crash_param[array_index_nospec(index, size)] = data;
1004 1005 1006
	return 0;
}

P
Paolo Bonzini 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
/*
 * The kvmclock and Hyper-V TSC page use similar formulas, and converting
 * between them is possible:
 *
 * kvmclock formula:
 *    nsec = (ticks - tsc_timestamp) * tsc_to_system_mul * 2^(tsc_shift-32)
 *           + system_time
 *
 * Hyper-V formula:
 *    nsec/100 = ticks * scale / 2^64 + offset
 *
 * When tsc_timestamp = system_time = 0, offset is zero in the Hyper-V formula.
 * By dividing the kvmclock formula by 100 and equating what's left we get:
 *    ticks * scale / 2^64 = ticks * tsc_to_system_mul * 2^(tsc_shift-32) / 100
 *            scale / 2^64 =         tsc_to_system_mul * 2^(tsc_shift-32) / 100
 *            scale        =         tsc_to_system_mul * 2^(32+tsc_shift) / 100
 *
 * Now expand the kvmclock formula and divide by 100:
 *    nsec = ticks * tsc_to_system_mul * 2^(tsc_shift-32)
 *           - tsc_timestamp * tsc_to_system_mul * 2^(tsc_shift-32)
 *           + system_time
 *    nsec/100 = ticks * tsc_to_system_mul * 2^(tsc_shift-32) / 100
 *               - tsc_timestamp * tsc_to_system_mul * 2^(tsc_shift-32) / 100
 *               + system_time / 100
 *
 * Replace tsc_to_system_mul * 2^(tsc_shift-32) / 100 by scale / 2^64:
 *    nsec/100 = ticks * scale / 2^64
 *               - tsc_timestamp * scale / 2^64
 *               + system_time / 100
 *
 * Equate with the Hyper-V formula so that ticks * scale / 2^64 cancels out:
 *    offset = system_time / 100 - tsc_timestamp * scale / 2^64
 *
 * These two equivalencies are implemented in this function.
 */
static bool compute_tsc_page_parameters(struct pvclock_vcpu_time_info *hv_clock,
1043
					struct ms_hyperv_tsc_page *tsc_ref)
P
Paolo Bonzini 已提交
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
{
	u64 max_mul;

	if (!(hv_clock->flags & PVCLOCK_TSC_STABLE_BIT))
		return false;

	/*
	 * check if scale would overflow, if so we use the time ref counter
	 *    tsc_to_system_mul * 2^(tsc_shift+32) / 100 >= 2^64
	 *    tsc_to_system_mul / 100 >= 2^(32-tsc_shift)
	 *    tsc_to_system_mul >= 100 * 2^(32-tsc_shift)
	 */
	max_mul = 100ull << (32 - hv_clock->tsc_shift);
	if (hv_clock->tsc_to_system_mul >= max_mul)
		return false;

	/*
	 * Otherwise compute the scale and offset according to the formulas
	 * derived above.
	 */
	tsc_ref->tsc_scale =
		mul_u64_u32_div(1ULL << (32 + hv_clock->tsc_shift),
				hv_clock->tsc_to_system_mul,
				100);

	tsc_ref->tsc_offset = hv_clock->system_time;
	do_div(tsc_ref->tsc_offset, 100);
	tsc_ref->tsc_offset -=
		mul_u64_u64_shr(hv_clock->tsc_timestamp, tsc_ref->tsc_scale, 64);
	return true;
}

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
/*
 * Don't touch TSC page values if the guest has opted for TSC emulation after
 * migration. KVM doesn't fully support reenlightenment notifications and TSC
 * access emulation and Hyper-V is known to expect the values in TSC page to
 * stay constant before TSC access emulation is disabled from guest side
 * (HV_X64_MSR_TSC_EMULATION_STATUS). KVM userspace is expected to preserve TSC
 * frequency and guest visible TSC value across migration (and prevent it when
 * TSC scaling is unsupported).
 */
static inline bool tsc_page_update_unsafe(struct kvm_hv *hv)
{
	return (hv->hv_tsc_page_status != HV_TSC_PAGE_GUEST_CHANGED) &&
		hv->hv_tsc_emulation_control;
}

P
Paolo Bonzini 已提交
1091 1092 1093
void kvm_hv_setup_tsc_page(struct kvm *kvm,
			   struct pvclock_vcpu_time_info *hv_clock)
{
1094
	struct kvm_hv *hv = to_kvm_hv(kvm);
P
Paolo Bonzini 已提交
1095 1096 1097 1098
	u32 tsc_seq;
	u64 gfn;

	BUILD_BUG_ON(sizeof(tsc_seq) != sizeof(hv->tsc_ref.tsc_sequence));
1099
	BUILD_BUG_ON(offsetof(struct ms_hyperv_tsc_page, tsc_sequence) != 0);
P
Paolo Bonzini 已提交
1100

1101 1102
	if (hv->hv_tsc_page_status == HV_TSC_PAGE_BROKEN ||
	    hv->hv_tsc_page_status == HV_TSC_PAGE_UNSET)
P
Paolo Bonzini 已提交
1103 1104
		return;

1105
	mutex_lock(&hv->hv_lock);
1106 1107 1108
	if (!(hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE))
		goto out_unlock;

P
Paolo Bonzini 已提交
1109 1110 1111 1112 1113 1114 1115
	gfn = hv->hv_tsc_page >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;
	/*
	 * Because the TSC parameters only vary when there is a
	 * change in the master clock, do not bother with caching.
	 */
	if (unlikely(kvm_read_guest(kvm, gfn_to_gpa(gfn),
				    &tsc_seq, sizeof(tsc_seq))))
1116
		goto out_err;
P
Paolo Bonzini 已提交
1117

1118 1119 1120 1121 1122 1123 1124 1125
	if (tsc_seq && tsc_page_update_unsafe(hv)) {
		if (kvm_read_guest(kvm, gfn_to_gpa(gfn), &hv->tsc_ref, sizeof(hv->tsc_ref)))
			goto out_err;

		hv->hv_tsc_page_status = HV_TSC_PAGE_SET;
		goto out_unlock;
	}

P
Paolo Bonzini 已提交
1126 1127 1128 1129 1130 1131 1132
	/*
	 * While we're computing and writing the parameters, force the
	 * guest to use the time reference count MSR.
	 */
	hv->tsc_ref.tsc_sequence = 0;
	if (kvm_write_guest(kvm, gfn_to_gpa(gfn),
			    &hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence)))
1133
		goto out_err;
P
Paolo Bonzini 已提交
1134 1135

	if (!compute_tsc_page_parameters(hv_clock, &hv->tsc_ref))
1136
		goto out_err;
P
Paolo Bonzini 已提交
1137 1138 1139 1140

	/* Ensure sequence is zero before writing the rest of the struct.  */
	smp_wmb();
	if (kvm_write_guest(kvm, gfn_to_gpa(gfn), &hv->tsc_ref, sizeof(hv->tsc_ref)))
1141
		goto out_err;
P
Paolo Bonzini 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

	/*
	 * Now switch to the TSC page mechanism by writing the sequence.
	 */
	tsc_seq++;
	if (tsc_seq == 0xFFFFFFFF || tsc_seq == 0)
		tsc_seq = 1;

	/* Write the struct entirely before the non-zero sequence.  */
	smp_wmb();

	hv->tsc_ref.tsc_sequence = tsc_seq;
1154 1155 1156 1157 1158 1159 1160 1161 1162
	if (kvm_write_guest(kvm, gfn_to_gpa(gfn),
			    &hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence)))
		goto out_err;

	hv->hv_tsc_page_status = HV_TSC_PAGE_SET;
	goto out_unlock;

out_err:
	hv->hv_tsc_page_status = HV_TSC_PAGE_BROKEN;
1163
out_unlock:
1164
	mutex_unlock(&hv->hv_lock);
P
Paolo Bonzini 已提交
1165 1166
}

1167 1168 1169 1170
void kvm_hv_invalidate_tsc_page(struct kvm *kvm)
{
	struct kvm_hv *hv = to_kvm_hv(kvm);
	u64 gfn;
1171
	int idx;
1172

1173
	if (hv->hv_tsc_page_status == HV_TSC_PAGE_BROKEN ||
1174 1175
	    hv->hv_tsc_page_status == HV_TSC_PAGE_UNSET ||
	    tsc_page_update_unsafe(hv))
1176 1177 1178 1179 1180 1181 1182
		return;

	mutex_lock(&hv->hv_lock);

	if (!(hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE))
		goto out_unlock;

1183 1184 1185 1186
	/* Preserve HV_TSC_PAGE_GUEST_CHANGED/HV_TSC_PAGE_HOST_CHANGED states */
	if (hv->hv_tsc_page_status == HV_TSC_PAGE_SET)
		hv->hv_tsc_page_status = HV_TSC_PAGE_UPDATING;

1187 1188 1189
	gfn = hv->hv_tsc_page >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;

	hv->tsc_ref.tsc_sequence = 0;
1190 1191 1192 1193 1194 1195

	/*
	 * Take the srcu lock as memslots will be accessed to check the gfn
	 * cache generation against the memslots generation.
	 */
	idx = srcu_read_lock(&kvm->srcu);
1196 1197 1198
	if (kvm_write_guest(kvm, gfn_to_gpa(gfn),
			    &hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence)))
		hv->hv_tsc_page_status = HV_TSC_PAGE_BROKEN;
1199
	srcu_read_unlock(&kvm->srcu, idx);
1200 1201 1202 1203 1204

out_unlock:
	mutex_unlock(&hv->hv_lock);
}

1205 1206 1207

static bool hv_check_msr_access(struct kvm_vcpu_hv *hv_vcpu, u32 msr)
{
1208 1209 1210 1211 1212 1213 1214 1215
	if (!hv_vcpu->enforce_cpuid)
		return true;

	switch (msr) {
	case HV_X64_MSR_GUEST_OS_ID:
	case HV_X64_MSR_HYPERCALL:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_HYPERCALL_AVAILABLE;
1216 1217 1218
	case HV_X64_MSR_VP_RUNTIME:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_VP_RUNTIME_AVAILABLE;
1219 1220 1221
	case HV_X64_MSR_TIME_REF_COUNT:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_TIME_REF_COUNT_AVAILABLE;
1222 1223 1224
	case HV_X64_MSR_VP_INDEX:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_VP_INDEX_AVAILABLE;
1225 1226 1227
	case HV_X64_MSR_RESET:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_RESET_AVAILABLE;
1228 1229 1230
	case HV_X64_MSR_REFERENCE_TSC:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_REFERENCE_TSC_AVAILABLE;
1231 1232 1233 1234 1235 1236 1237 1238
	case HV_X64_MSR_SCONTROL:
	case HV_X64_MSR_SVERSION:
	case HV_X64_MSR_SIEFP:
	case HV_X64_MSR_SIMP:
	case HV_X64_MSR_EOM:
	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
		return hv_vcpu->cpuid_cache.features_eax &
			HV_MSR_SYNIC_AVAILABLE;
1239 1240 1241 1242
	default:
		break;
	}

1243 1244 1245
	return true;
}

1246 1247
static int kvm_hv_set_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data,
			     bool host)
1248 1249
{
	struct kvm *kvm = vcpu->kvm;
1250
	struct kvm_hv *hv = to_kvm_hv(kvm);
1251

1252 1253 1254
	if (unlikely(!host && !hv_check_msr_access(to_hv_vcpu(vcpu), msr)))
		return 1;

1255 1256 1257 1258 1259 1260 1261 1262
	switch (msr) {
	case HV_X64_MSR_GUEST_OS_ID:
		hv->hv_guest_os_id = data;
		/* setting guest os id to zero disables hypercall page */
		if (!hv->hv_guest_os_id)
			hv->hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
		break;
	case HV_X64_MSR_HYPERCALL: {
1263 1264 1265
		u8 instructions[9];
		int i = 0;
		u64 addr;
1266 1267 1268 1269 1270 1271 1272 1273

		/* if guest os id is not set hypercall should remain disabled */
		if (!hv->hv_guest_os_id)
			break;
		if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
			hv->hv_hypercall = data;
			break;
		}
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

		/*
		 * If Xen and Hyper-V hypercalls are both enabled, disambiguate
		 * the same way Xen itself does, by setting the bit 31 of EAX
		 * which is RsvdZ in the 32-bit Hyper-V hypercall ABI and just
		 * going to be clobbered on 64-bit.
		 */
		if (kvm_xen_hypercall_enabled(kvm)) {
			/* orl $0x80000000, %eax */
			instructions[i++] = 0x0d;
			instructions[i++] = 0x00;
			instructions[i++] = 0x00;
			instructions[i++] = 0x00;
			instructions[i++] = 0x80;
		}

		/* vmcall/vmmcall */
		static_call(kvm_x86_patch_hypercall)(vcpu, instructions + i);
		i += 3;

		/* ret */
		((unsigned char *)instructions)[i++] = 0xc3;

		addr = data & HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_MASK;
		if (kvm_vcpu_write_guest(vcpu, addr, instructions, i))
1299 1300 1301 1302
			return 1;
		hv->hv_hypercall = data;
		break;
	}
P
Paolo Bonzini 已提交
1303
	case HV_X64_MSR_REFERENCE_TSC:
1304
		hv->hv_tsc_page = data;
1305 1306 1307 1308 1309
		if (hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE) {
			if (!host)
				hv->hv_tsc_page_status = HV_TSC_PAGE_GUEST_CHANGED;
			else
				hv->hv_tsc_page_status = HV_TSC_PAGE_HOST_CHANGED;
P
Paolo Bonzini 已提交
1310
			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1311 1312 1313
		} else {
			hv->hv_tsc_page_status = HV_TSC_PAGE_UNSET;
		}
1314
		break;
1315
	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1316
		return kvm_hv_msr_set_crash_data(kvm,
1317 1318 1319
						 msr - HV_X64_MSR_CRASH_P0,
						 data);
	case HV_X64_MSR_CRASH_CTL:
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
		if (host)
			return kvm_hv_msr_set_crash_ctl(kvm, data);

		if (data & HV_CRASH_CTL_CRASH_NOTIFY) {
			vcpu_debug(vcpu, "hv crash (0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n",
				   hv->hv_crash_param[0],
				   hv->hv_crash_param[1],
				   hv->hv_crash_param[2],
				   hv->hv_crash_param[3],
				   hv->hv_crash_param[4]);

			/* Send notification about crash to user space */
			kvm_make_request(KVM_REQ_HV_CRASH, vcpu);
		}
		break;
1335 1336 1337 1338 1339 1340
	case HV_X64_MSR_RESET:
		if (data == 1) {
			vcpu_debug(vcpu, "hyper-v reset requested\n");
			kvm_make_request(KVM_REQ_HV_RESET, vcpu);
		}
		break;
1341 1342 1343 1344 1345 1346 1347
	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
		hv->hv_reenlightenment_control = data;
		break;
	case HV_X64_MSR_TSC_EMULATION_CONTROL:
		hv->hv_tsc_emulation_control = data;
		break;
	case HV_X64_MSR_TSC_EMULATION_STATUS:
1348 1349 1350
		if (data && !host)
			return 1;

1351 1352
		hv->hv_tsc_emulation_status = data;
		break;
1353 1354 1355 1356 1357
	case HV_X64_MSR_TIME_REF_COUNT:
		/* read-only, but still ignore it if host-initiated */
		if (!host)
			return 1;
		break;
1358 1359 1360
	case HV_X64_MSR_SYNDBG_OPTIONS:
	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
		return syndbg_set_msr(vcpu, msr, data, host);
1361
	default:
1362
		vcpu_unimpl(vcpu, "Hyper-V unhandled wrmsr: 0x%x data 0x%llx\n",
1363 1364 1365 1366 1367 1368
			    msr, data);
		return 1;
	}
	return 0;
}

1369 1370 1371
/* Calculate cpu time spent by current task in 100ns units */
static u64 current_task_runtime_100ns(void)
{
1372
	u64 utime, stime;
1373 1374

	task_cputime_adjusted(current, &utime, &stime);
1375 1376

	return div_u64(utime + stime, 100);
1377 1378 1379
}

static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1380
{
1381
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1382

1383 1384 1385
	if (unlikely(!host && !hv_check_msr_access(hv_vcpu, msr)))
		return 1;

1386
	switch (msr) {
1387
	case HV_X64_MSR_VP_INDEX: {
1388
		struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
1389 1390 1391 1392
		int vcpu_idx = kvm_vcpu_get_idx(vcpu);
		u32 new_vp_index = (u32)data;

		if (!host || new_vp_index >= KVM_MAX_VCPUS)
1393
			return 1;
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

		if (new_vp_index == hv_vcpu->vp_index)
			return 0;

		/*
		 * The VP index is initialized to vcpu_index by
		 * kvm_hv_vcpu_postcreate so they initially match.  Now the
		 * VP index is changing, adjust num_mismatched_vp_indexes if
		 * it now matches or no longer matches vcpu_idx.
		 */
		if (hv_vcpu->vp_index == vcpu_idx)
			atomic_inc(&hv->num_mismatched_vp_indexes);
		else if (new_vp_index == vcpu_idx)
			atomic_dec(&hv->num_mismatched_vp_indexes);

		hv_vcpu->vp_index = new_vp_index;
1410
		break;
1411
	}
1412
	case HV_X64_MSR_VP_ASSIST_PAGE: {
1413 1414 1415
		u64 gfn;
		unsigned long addr;

1416
		if (!(data & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE)) {
1417
			hv_vcpu->hv_vapic = data;
1418
			if (kvm_lapic_enable_pv_eoi(vcpu, 0, 0))
1419 1420 1421
				return 1;
			break;
		}
1422
		gfn = data >> HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_SHIFT;
1423 1424 1425
		addr = kvm_vcpu_gfn_to_hva(vcpu, gfn);
		if (kvm_is_error_hva(addr))
			return 1;
1426 1427

		/*
1428
		 * Clear apic_assist portion of struct hv_vp_assist_page
1429 1430 1431
		 * only, there can be valuable data in the rest which needs
		 * to be preserved e.g. on migration.
		 */
1432
		if (__put_user(0, (u32 __user *)addr))
1433
			return 1;
1434
		hv_vcpu->hv_vapic = data;
1435 1436
		kvm_vcpu_mark_page_dirty(vcpu, gfn);
		if (kvm_lapic_enable_pv_eoi(vcpu,
1437 1438
					    gfn_to_gpa(gfn) | KVM_MSR_ENABLED,
					    sizeof(struct hv_vp_assist_page)))
1439 1440 1441 1442 1443 1444 1445 1446 1447
			return 1;
		break;
	}
	case HV_X64_MSR_EOI:
		return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
	case HV_X64_MSR_ICR:
		return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
	case HV_X64_MSR_TPR:
		return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1448 1449 1450
	case HV_X64_MSR_VP_RUNTIME:
		if (!host)
			return 1;
1451
		hv_vcpu->runtime_offset = data - current_task_runtime_100ns();
1452
		break;
1453 1454 1455 1456 1457 1458
	case HV_X64_MSR_SCONTROL:
	case HV_X64_MSR_SVERSION:
	case HV_X64_MSR_SIEFP:
	case HV_X64_MSR_SIMP:
	case HV_X64_MSR_EOM:
	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1459
		return synic_set_msr(to_hv_synic(vcpu), msr, data, host);
A
Andrey Smetanin 已提交
1460 1461 1462 1463 1464 1465
	case HV_X64_MSR_STIMER0_CONFIG:
	case HV_X64_MSR_STIMER1_CONFIG:
	case HV_X64_MSR_STIMER2_CONFIG:
	case HV_X64_MSR_STIMER3_CONFIG: {
		int timer_index = (msr - HV_X64_MSR_STIMER0_CONFIG)/2;

1466
		return stimer_set_config(to_hv_stimer(vcpu, timer_index),
A
Andrey Smetanin 已提交
1467 1468 1469 1470 1471 1472 1473 1474
					 data, host);
	}
	case HV_X64_MSR_STIMER0_COUNT:
	case HV_X64_MSR_STIMER1_COUNT:
	case HV_X64_MSR_STIMER2_COUNT:
	case HV_X64_MSR_STIMER3_COUNT: {
		int timer_index = (msr - HV_X64_MSR_STIMER0_COUNT)/2;

1475
		return stimer_set_count(to_hv_stimer(vcpu, timer_index),
A
Andrey Smetanin 已提交
1476 1477
					data, host);
	}
1478 1479 1480 1481 1482 1483
	case HV_X64_MSR_TSC_FREQUENCY:
	case HV_X64_MSR_APIC_FREQUENCY:
		/* read-only, but still ignore it if host-initiated */
		if (!host)
			return 1;
		break;
1484
	default:
1485
		vcpu_unimpl(vcpu, "Hyper-V unhandled wrmsr: 0x%x data 0x%llx\n",
1486 1487 1488 1489 1490 1491 1492
			    msr, data);
		return 1;
	}

	return 0;
}

1493 1494
static int kvm_hv_get_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
			     bool host)
1495 1496 1497
{
	u64 data = 0;
	struct kvm *kvm = vcpu->kvm;
1498
	struct kvm_hv *hv = to_kvm_hv(kvm);
1499

1500 1501 1502
	if (unlikely(!host && !hv_check_msr_access(to_hv_vcpu(vcpu), msr)))
		return 1;

1503 1504 1505 1506 1507 1508 1509
	switch (msr) {
	case HV_X64_MSR_GUEST_OS_ID:
		data = hv->hv_guest_os_id;
		break;
	case HV_X64_MSR_HYPERCALL:
		data = hv->hv_hypercall;
		break;
1510 1511
	case HV_X64_MSR_TIME_REF_COUNT:
		data = get_time_ref_counter(kvm);
1512 1513 1514 1515
		break;
	case HV_X64_MSR_REFERENCE_TSC:
		data = hv->hv_tsc_page;
		break;
1516
	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1517
		return kvm_hv_msr_get_crash_data(kvm,
1518 1519 1520
						 msr - HV_X64_MSR_CRASH_P0,
						 pdata);
	case HV_X64_MSR_CRASH_CTL:
1521
		return kvm_hv_msr_get_crash_ctl(kvm, pdata);
1522 1523 1524
	case HV_X64_MSR_RESET:
		data = 0;
		break;
1525 1526 1527 1528 1529 1530 1531 1532 1533
	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
		data = hv->hv_reenlightenment_control;
		break;
	case HV_X64_MSR_TSC_EMULATION_CONTROL:
		data = hv->hv_tsc_emulation_control;
		break;
	case HV_X64_MSR_TSC_EMULATION_STATUS:
		data = hv->hv_tsc_emulation_status;
		break;
1534 1535 1536
	case HV_X64_MSR_SYNDBG_OPTIONS:
	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
		return syndbg_get_msr(vcpu, msr, pdata, host);
1537 1538 1539 1540 1541 1542 1543 1544 1545
	default:
		vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
		return 1;
	}

	*pdata = data;
	return 0;
}

1546 1547
static int kvm_hv_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
			  bool host)
1548 1549
{
	u64 data = 0;
1550
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1551

1552 1553 1554
	if (unlikely(!host && !hv_check_msr_access(hv_vcpu, msr)))
		return 1;

1555
	switch (msr) {
1556
	case HV_X64_MSR_VP_INDEX:
1557
		data = hv_vcpu->vp_index;
1558 1559 1560 1561 1562 1563 1564
		break;
	case HV_X64_MSR_EOI:
		return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
	case HV_X64_MSR_ICR:
		return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
	case HV_X64_MSR_TPR:
		return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1565
	case HV_X64_MSR_VP_ASSIST_PAGE:
1566
		data = hv_vcpu->hv_vapic;
1567
		break;
1568
	case HV_X64_MSR_VP_RUNTIME:
1569
		data = current_task_runtime_100ns() + hv_vcpu->runtime_offset;
1570
		break;
1571 1572 1573 1574 1575 1576
	case HV_X64_MSR_SCONTROL:
	case HV_X64_MSR_SVERSION:
	case HV_X64_MSR_SIEFP:
	case HV_X64_MSR_SIMP:
	case HV_X64_MSR_EOM:
	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1577
		return synic_get_msr(to_hv_synic(vcpu), msr, pdata, host);
A
Andrey Smetanin 已提交
1578 1579 1580 1581 1582 1583
	case HV_X64_MSR_STIMER0_CONFIG:
	case HV_X64_MSR_STIMER1_CONFIG:
	case HV_X64_MSR_STIMER2_CONFIG:
	case HV_X64_MSR_STIMER3_CONFIG: {
		int timer_index = (msr - HV_X64_MSR_STIMER0_CONFIG)/2;

1584
		return stimer_get_config(to_hv_stimer(vcpu, timer_index),
A
Andrey Smetanin 已提交
1585 1586 1587 1588 1589 1590 1591 1592
					 pdata);
	}
	case HV_X64_MSR_STIMER0_COUNT:
	case HV_X64_MSR_STIMER1_COUNT:
	case HV_X64_MSR_STIMER2_COUNT:
	case HV_X64_MSR_STIMER3_COUNT: {
		int timer_index = (msr - HV_X64_MSR_STIMER0_COUNT)/2;

1593
		return stimer_get_count(to_hv_stimer(vcpu, timer_index),
A
Andrey Smetanin 已提交
1594 1595
					pdata);
	}
1596 1597 1598 1599 1600 1601
	case HV_X64_MSR_TSC_FREQUENCY:
		data = (u64)vcpu->arch.virtual_tsc_khz * 1000;
		break;
	case HV_X64_MSR_APIC_FREQUENCY:
		data = APIC_BUS_FREQUENCY;
		break;
1602 1603 1604 1605 1606 1607 1608 1609
	default:
		vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
		return 1;
	}
	*pdata = data;
	return 0;
}

1610
int kvm_hv_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1611
{
1612 1613
	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);

1614 1615 1616
	if (!host && !vcpu->arch.hyperv_enabled)
		return 1;

1617 1618 1619 1620 1621
	if (!to_hv_vcpu(vcpu)) {
		if (kvm_hv_vcpu_init(vcpu))
			return 1;
	}

1622 1623 1624
	if (kvm_hv_msr_partition_wide(msr)) {
		int r;

1625
		mutex_lock(&hv->hv_lock);
1626
		r = kvm_hv_set_msr_pw(vcpu, msr, data, host);
1627
		mutex_unlock(&hv->hv_lock);
1628 1629
		return r;
	} else
1630
		return kvm_hv_set_msr(vcpu, msr, data, host);
1631 1632
}

1633
int kvm_hv_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
1634
{
1635 1636
	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);

1637 1638 1639
	if (!host && !vcpu->arch.hyperv_enabled)
		return 1;

1640 1641 1642 1643 1644
	if (!to_hv_vcpu(vcpu)) {
		if (kvm_hv_vcpu_init(vcpu))
			return 1;
	}

1645 1646 1647
	if (kvm_hv_msr_partition_wide(msr)) {
		int r;

1648
		mutex_lock(&hv->hv_lock);
1649
		r = kvm_hv_get_msr_pw(vcpu, msr, pdata, host);
1650
		mutex_unlock(&hv->hv_lock);
1651 1652
		return r;
	} else
1653
		return kvm_hv_get_msr(vcpu, msr, pdata, host);
1654 1655
}

1656 1657 1658
static __always_inline unsigned long *sparse_set_to_vcpu_mask(
	struct kvm *kvm, u64 *sparse_banks, u64 valid_bank_mask,
	u64 *vp_bitmap, unsigned long *vcpu_bitmap)
1659
{
1660
	struct kvm_hv *hv = to_kvm_hv(kvm);
1661 1662
	struct kvm_vcpu *vcpu;
	int i, bank, sbank = 0;
1663

1664 1665 1666 1667 1668
	memset(vp_bitmap, 0,
	       KVM_HV_MAX_SPARSE_VCPU_SET_BITS * sizeof(*vp_bitmap));
	for_each_set_bit(bank, (unsigned long *)&valid_bank_mask,
			 KVM_HV_MAX_SPARSE_VCPU_SET_BITS)
		vp_bitmap[bank] = sparse_banks[sbank++];
1669

1670 1671 1672 1673
	if (likely(!atomic_read(&hv->num_mismatched_vp_indexes))) {
		/* for all vcpus vp_index == vcpu_idx */
		return (unsigned long *)vp_bitmap;
	}
1674

1675 1676
	bitmap_zero(vcpu_bitmap, KVM_MAX_VCPUS);
	kvm_for_each_vcpu(i, vcpu, kvm) {
1677
		if (test_bit(kvm_hv_get_vpindex(vcpu), (unsigned long *)vp_bitmap))
1678 1679 1680
			__set_bit(i, vcpu_bitmap);
	}
	return vcpu_bitmap;
1681 1682
}

1683 1684 1685 1686 1687 1688 1689 1690 1691
struct kvm_hv_hcall {
	u64 param;
	u64 ingpa;
	u64 outgpa;
	u16 code;
	u16 rep_cnt;
	u16 rep_idx;
	bool fast;
	bool rep;
1692
	sse128_t xmm[HV_HYPERCALL_MAX_XMM_REGISTERS];
1693 1694 1695
};

static u64 kvm_hv_flush_tlb(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc, bool ex)
1696
{
1697 1698
	int i;
	gpa_t gpa;
1699
	struct kvm *kvm = vcpu->kvm;
1700
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1701
	struct hv_tlb_flush_ex flush_ex;
1702
	struct hv_tlb_flush flush;
1703 1704 1705
	u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
	DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
	unsigned long *vcpu_mask;
1706
	u64 valid_bank_mask;
1707
	u64 sparse_banks[64];
1708
	int sparse_banks_len;
1709
	bool all_cpus;
1710

1711
	if (!ex) {
1712 1713 1714 1715 1716 1717 1718 1719 1720
		if (hc->fast) {
			flush.address_space = hc->ingpa;
			flush.flags = hc->outgpa;
			flush.processor_mask = sse128_lo(hc->xmm[0]);
		} else {
			if (unlikely(kvm_read_guest(kvm, hc->ingpa,
						    &flush, sizeof(flush))))
				return HV_STATUS_INVALID_HYPERCALL_INPUT;
		}
1721

1722 1723 1724
		trace_kvm_hv_flush_tlb(flush.processor_mask,
				       flush.address_space, flush.flags);

1725
		valid_bank_mask = BIT_ULL(0);
1726
		sparse_banks[0] = flush.processor_mask;
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736

		/*
		 * Work around possible WS2012 bug: it sends hypercalls
		 * with processor_mask = 0x0 and HV_FLUSH_ALL_PROCESSORS clear,
		 * while also expecting us to flush something and crashing if
		 * we don't. Let's treat processor_mask == 0 same as
		 * HV_FLUSH_ALL_PROCESSORS.
		 */
		all_cpus = (flush.flags & HV_FLUSH_ALL_PROCESSORS) ||
			flush.processor_mask == 0;
1737
	} else {
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
		if (hc->fast) {
			flush_ex.address_space = hc->ingpa;
			flush_ex.flags = hc->outgpa;
			memcpy(&flush_ex.hv_vp_set,
			       &hc->xmm[0], sizeof(hc->xmm[0]));
		} else {
			if (unlikely(kvm_read_guest(kvm, hc->ingpa, &flush_ex,
						    sizeof(flush_ex))))
				return HV_STATUS_INVALID_HYPERCALL_INPUT;
		}
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757

		trace_kvm_hv_flush_tlb_ex(flush_ex.hv_vp_set.valid_bank_mask,
					  flush_ex.hv_vp_set.format,
					  flush_ex.address_space,
					  flush_ex.flags);

		valid_bank_mask = flush_ex.hv_vp_set.valid_bank_mask;
		all_cpus = flush_ex.hv_vp_set.format !=
			HV_GENERIC_SET_SPARSE_4K;

1758
		sparse_banks_len = bitmap_weight((unsigned long *)&valid_bank_mask, 64);
1759 1760 1761 1762

		if (!sparse_banks_len && !all_cpus)
			goto ret_success;

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
		if (!all_cpus) {
			if (hc->fast) {
				if (sparse_banks_len > HV_HYPERCALL_MAX_XMM_REGISTERS - 1)
					return HV_STATUS_INVALID_HYPERCALL_INPUT;
				for (i = 0; i < sparse_banks_len; i += 2) {
					sparse_banks[i] = sse128_lo(hc->xmm[i / 2 + 1]);
					sparse_banks[i + 1] = sse128_hi(hc->xmm[i / 2 + 1]);
				}
			} else {
				gpa = hc->ingpa + offsetof(struct hv_tlb_flush_ex,
							   hv_vp_set.bank_contents);
				if (unlikely(kvm_read_guest(kvm, gpa, sparse_banks,
							    sparse_banks_len *
							    sizeof(sparse_banks[0]))))
					return HV_STATUS_INVALID_HYPERCALL_INPUT;
			}
		}
1780
	}
1781

1782
	cpumask_clear(&hv_vcpu->tlb_flush);
1783

1784 1785 1786
	vcpu_mask = all_cpus ? NULL :
		sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask,
					vp_bitmap, vcpu_bitmap);
1787

1788
	/*
1789 1790
	 * vcpu->arch.cr3 may not be up-to-date for running vCPUs so we can't
	 * analyze it here, flush TLB regardless of the specified address space.
1791
	 */
1792
	kvm_make_vcpus_request_mask(kvm, KVM_REQ_HV_TLB_FLUSH,
1793
				    NULL, vcpu_mask, &hv_vcpu->tlb_flush);
1794

1795
ret_success:
1796
	/* We always do full TLB flush, set 'Reps completed' = 'Rep Count' */
1797
	return (u64)HV_STATUS_SUCCESS |
1798
		((u64)hc->rep_cnt << HV_HYPERCALL_REP_COMP_OFFSET);
1799 1800
}

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
static void kvm_send_ipi_to_many(struct kvm *kvm, u32 vector,
				 unsigned long *vcpu_bitmap)
{
	struct kvm_lapic_irq irq = {
		.delivery_mode = APIC_DM_FIXED,
		.vector = vector
	};
	struct kvm_vcpu *vcpu;
	int i;

	kvm_for_each_vcpu(i, vcpu, kvm) {
		if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
			continue;

		/* We fail only when APIC is disabled */
		kvm_apic_set_irq(vcpu, &irq, NULL);
	}
}

1820
static u64 kvm_hv_send_ipi(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc, bool ex)
1821
{
1822
	struct kvm *kvm = vcpu->kvm;
1823 1824
	struct hv_send_ipi_ex send_ipi_ex;
	struct hv_send_ipi send_ipi;
1825 1826 1827
	u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
	DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
	unsigned long *vcpu_mask;
1828 1829
	unsigned long valid_bank_mask;
	u64 sparse_banks[64];
1830 1831
	int sparse_banks_len;
	u32 vector;
1832 1833 1834
	bool all_cpus;

	if (!ex) {
1835 1836
		if (!hc->fast) {
			if (unlikely(kvm_read_guest(kvm, hc->ingpa, &send_ipi,
1837 1838 1839
						    sizeof(send_ipi))))
				return HV_STATUS_INVALID_HYPERCALL_INPUT;
			sparse_banks[0] = send_ipi.cpu_mask;
1840
			vector = send_ipi.vector;
1841 1842
		} else {
			/* 'reserved' part of hv_send_ipi should be 0 */
1843
			if (unlikely(hc->ingpa >> 32 != 0))
1844
				return HV_STATUS_INVALID_HYPERCALL_INPUT;
1845 1846
			sparse_banks[0] = hc->outgpa;
			vector = (u32)hc->ingpa;
1847 1848 1849 1850
		}
		all_cpus = false;
		valid_bank_mask = BIT_ULL(0);

1851
		trace_kvm_hv_send_ipi(vector, sparse_banks[0]);
1852
	} else {
1853
		if (unlikely(kvm_read_guest(kvm, hc->ingpa, &send_ipi_ex,
1854 1855 1856 1857 1858 1859 1860
					    sizeof(send_ipi_ex))))
			return HV_STATUS_INVALID_HYPERCALL_INPUT;

		trace_kvm_hv_send_ipi_ex(send_ipi_ex.vector,
					 send_ipi_ex.vp_set.format,
					 send_ipi_ex.vp_set.valid_bank_mask);

1861
		vector = send_ipi_ex.vector;
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
		valid_bank_mask = send_ipi_ex.vp_set.valid_bank_mask;
		sparse_banks_len = bitmap_weight(&valid_bank_mask, 64) *
			sizeof(sparse_banks[0]);

		all_cpus = send_ipi_ex.vp_set.format == HV_GENERIC_SET_ALL;

		if (!sparse_banks_len)
			goto ret_success;

		if (!all_cpus &&
		    kvm_read_guest(kvm,
1873 1874
				   hc->ingpa + offsetof(struct hv_send_ipi_ex,
							vp_set.bank_contents),
1875 1876 1877 1878 1879
				   sparse_banks,
				   sparse_banks_len))
			return HV_STATUS_INVALID_HYPERCALL_INPUT;
	}

1880
	if ((vector < HV_IPI_LOW_VECTOR) || (vector > HV_IPI_HIGH_VECTOR))
1881 1882
		return HV_STATUS_INVALID_HYPERCALL_INPUT;

1883 1884 1885
	vcpu_mask = all_cpus ? NULL :
		sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask,
					vp_bitmap, vcpu_bitmap);
1886

1887
	kvm_send_ipi_to_many(kvm, vector, vcpu_mask);
1888 1889 1890 1891 1892

ret_success:
	return HV_STATUS_SUCCESS;
}

1893 1894 1895
void kvm_hv_set_cpuid(struct kvm_vcpu *vcpu)
{
	struct kvm_cpuid_entry2 *entry;
1896
	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1897 1898

	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_INTERFACE, 0);
1899
	if (entry && entry->eax == HYPERV_CPUID_SIGNATURE_EAX) {
1900
		vcpu->arch.hyperv_enabled = true;
1901
	} else {
1902
		vcpu->arch.hyperv_enabled = false;
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
		return;
	}

	if (!to_hv_vcpu(vcpu) && kvm_hv_vcpu_init(vcpu))
		return;

	hv_vcpu = to_hv_vcpu(vcpu);

	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_FEATURES, 0);
	if (entry) {
		hv_vcpu->cpuid_cache.features_eax = entry->eax;
		hv_vcpu->cpuid_cache.features_ebx = entry->ebx;
		hv_vcpu->cpuid_cache.features_edx = entry->edx;
	} else {
		hv_vcpu->cpuid_cache.features_eax = 0;
		hv_vcpu->cpuid_cache.features_ebx = 0;
		hv_vcpu->cpuid_cache.features_edx = 0;
	}

	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_ENLIGHTMENT_INFO, 0);
	if (entry) {
		hv_vcpu->cpuid_cache.enlightenments_eax = entry->eax;
		hv_vcpu->cpuid_cache.enlightenments_ebx = entry->ebx;
	} else {
		hv_vcpu->cpuid_cache.enlightenments_eax = 0;
		hv_vcpu->cpuid_cache.enlightenments_ebx = 0;
	}

	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES, 0);
	if (entry)
		hv_vcpu->cpuid_cache.syndbg_cap_eax = entry->eax;
	else
		hv_vcpu->cpuid_cache.syndbg_cap_eax = 0;
1936 1937
}

1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
int kvm_hv_set_enforce_cpuid(struct kvm_vcpu *vcpu, bool enforce)
{
	struct kvm_vcpu_hv *hv_vcpu;
	int ret = 0;

	if (!to_hv_vcpu(vcpu)) {
		if (enforce) {
			ret = kvm_hv_vcpu_init(vcpu);
			if (ret)
				return ret;
		} else {
			return 0;
		}
	}

	hv_vcpu = to_hv_vcpu(vcpu);
	hv_vcpu->enforce_cpuid = enforce;

	return ret;
}

1959
bool kvm_hv_hypercall_enabled(struct kvm_vcpu *vcpu)
1960
{
1961
	return vcpu->arch.hyperv_enabled && to_kvm_hv(vcpu->kvm)->hv_guest_os_id;
1962 1963
}

1964 1965 1966 1967 1968 1969
static void kvm_hv_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)
{
	bool longmode;

	longmode = is_64_bit_mode(vcpu);
	if (longmode)
1970
		kvm_rax_write(vcpu, result);
1971
	else {
1972 1973
		kvm_rdx_write(vcpu, result >> 32);
		kvm_rax_write(vcpu, result & 0xffffffff);
1974 1975 1976
	}
}

1977
static int kvm_hv_hypercall_complete(struct kvm_vcpu *vcpu, u64 result)
1978
{
1979 1980
	kvm_hv_hypercall_set_result(vcpu, result);
	++vcpu->stat.hypercalls;
1981
	return kvm_skip_emulated_instruction(vcpu);
1982 1983
}

1984 1985 1986 1987 1988
static int kvm_hv_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
{
	return kvm_hv_hypercall_complete(vcpu, vcpu->run->hyperv.u.hcall.result);
}

1989
static u16 kvm_hvcall_signal_event(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc)
1990
{
1991
	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
1992 1993
	struct eventfd_ctx *eventfd;

1994
	if (unlikely(!hc->fast)) {
1995
		int ret;
1996
		gpa_t gpa = hc->ingpa;
1997

1998 1999
		if ((gpa & (__alignof__(hc->ingpa) - 1)) ||
		    offset_in_page(gpa) + sizeof(hc->ingpa) > PAGE_SIZE)
2000 2001
			return HV_STATUS_INVALID_ALIGNMENT;

2002 2003
		ret = kvm_vcpu_read_guest(vcpu, gpa,
					  &hc->ingpa, sizeof(hc->ingpa));
2004 2005 2006 2007 2008 2009 2010 2011 2012
		if (ret < 0)
			return HV_STATUS_INVALID_ALIGNMENT;
	}

	/*
	 * Per spec, bits 32-47 contain the extra "flag number".  However, we
	 * have no use for it, and in all known usecases it is zero, so just
	 * report lookup failure if it isn't.
	 */
2013
	if (hc->ingpa & 0xffff00000000ULL)
2014 2015
		return HV_STATUS_INVALID_PORT_ID;
	/* remaining bits are reserved-zero */
2016
	if (hc->ingpa & ~KVM_HYPERV_CONN_ID_MASK)
2017 2018
		return HV_STATUS_INVALID_HYPERCALL_INPUT;

2019 2020
	/* the eventfd is protected by vcpu->kvm->srcu, but conn_to_evt isn't */
	rcu_read_lock();
2021
	eventfd = idr_find(&hv->conn_to_evt, hc->ingpa);
2022
	rcu_read_unlock();
2023 2024 2025 2026 2027 2028 2029
	if (!eventfd)
		return HV_STATUS_INVALID_PORT_ID;

	eventfd_signal(eventfd, 1);
	return HV_STATUS_SUCCESS;
}

2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
static bool is_xmm_fast_hypercall(struct kvm_hv_hcall *hc)
{
	switch (hc->code) {
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST:
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE:
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST_EX:
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX:
		return true;
	}

	return false;
}

static void kvm_hv_hypercall_read_xmm(struct kvm_hv_hcall *hc)
{
	int reg;

	kvm_fpu_get();
	for (reg = 0; reg < HV_HYPERCALL_MAX_XMM_REGISTERS; reg++)
		_kvm_read_sse_reg(reg, &hc->xmm[reg]);
	kvm_fpu_put();
}

2053 2054
int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
{
2055 2056
	struct kvm_hv_hcall hc;
	u64 ret = HV_STATUS_SUCCESS;
2057 2058 2059 2060 2061

	/*
	 * hypercall generates UD from non zero cpl and real mode
	 * per HYPER-V spec
	 */
2062
	if (static_call(kvm_x86_get_cpl)(vcpu) != 0 || !is_protmode(vcpu)) {
2063
		kvm_queue_exception(vcpu, UD_VECTOR);
2064
		return 1;
2065 2066
	}

2067 2068
#ifdef CONFIG_X86_64
	if (is_64_bit_mode(vcpu)) {
2069 2070 2071
		hc.param = kvm_rcx_read(vcpu);
		hc.ingpa = kvm_rdx_read(vcpu);
		hc.outgpa = kvm_r8_read(vcpu);
2072 2073 2074
	} else
#endif
	{
2075 2076 2077 2078 2079 2080
		hc.param = ((u64)kvm_rdx_read(vcpu) << 32) |
			    (kvm_rax_read(vcpu) & 0xffffffff);
		hc.ingpa = ((u64)kvm_rbx_read(vcpu) << 32) |
			    (kvm_rcx_read(vcpu) & 0xffffffff);
		hc.outgpa = ((u64)kvm_rdi_read(vcpu) << 32) |
			     (kvm_rsi_read(vcpu) & 0xffffffff);
2081 2082
	}

2083 2084 2085 2086 2087
	hc.code = hc.param & 0xffff;
	hc.fast = !!(hc.param & HV_HYPERCALL_FAST_BIT);
	hc.rep_cnt = (hc.param >> HV_HYPERCALL_REP_COMP_OFFSET) & 0xfff;
	hc.rep_idx = (hc.param >> HV_HYPERCALL_REP_START_OFFSET) & 0xfff;
	hc.rep = !!(hc.rep_cnt || hc.rep_idx);
2088

2089 2090 2091
	if (hc.fast && is_xmm_fast_hypercall(&hc))
		kvm_hv_hypercall_read_xmm(&hc);

2092 2093
	trace_kvm_hv_hypercall(hc.code, hc.fast, hc.rep_cnt, hc.rep_idx,
			       hc.ingpa, hc.outgpa);
2094

2095
	switch (hc.code) {
2096
	case HVCALL_NOTIFY_LONG_SPIN_WAIT:
2097
		if (unlikely(hc.rep)) {
2098 2099 2100
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2101
		kvm_vcpu_on_spin(vcpu, true);
2102
		break;
2103
	case HVCALL_SIGNAL_EVENT:
2104
		if (unlikely(hc.rep)) {
2105 2106 2107
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2108
		ret = kvm_hvcall_signal_event(vcpu, &hc);
2109
		if (ret != HV_STATUS_INVALID_PORT_ID)
2110
			break;
2111
		fallthrough;	/* maybe userspace knows this conn_id */
2112
	case HVCALL_POST_MESSAGE:
2113
		/* don't bother userspace if it has no way to handle it */
2114
		if (unlikely(hc.rep || !to_hv_synic(vcpu)->active)) {
2115
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2116 2117
			break;
		}
2118 2119
		vcpu->run->exit_reason = KVM_EXIT_HYPERV;
		vcpu->run->hyperv.type = KVM_EXIT_HYPERV_HCALL;
2120 2121 2122
		vcpu->run->hyperv.u.hcall.input = hc.param;
		vcpu->run->hyperv.u.hcall.params[0] = hc.ingpa;
		vcpu->run->hyperv.u.hcall.params[1] = hc.outgpa;
2123 2124 2125
		vcpu->arch.complete_userspace_io =
				kvm_hv_hypercall_complete_userspace;
		return 0;
2126
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST:
2127
		if (unlikely(!hc.rep_cnt || hc.rep_idx)) {
2128 2129 2130
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2131
		ret = kvm_hv_flush_tlb(vcpu, &hc, false);
2132 2133
		break;
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE:
2134
		if (unlikely(hc.rep)) {
2135 2136 2137
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2138
		ret = kvm_hv_flush_tlb(vcpu, &hc, false);
2139 2140
		break;
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST_EX:
2141
		if (unlikely(!hc.rep_cnt || hc.rep_idx)) {
2142 2143 2144
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2145
		ret = kvm_hv_flush_tlb(vcpu, &hc, true);
2146 2147
		break;
	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX:
2148
		if (unlikely(hc.rep)) {
2149 2150 2151
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2152
		ret = kvm_hv_flush_tlb(vcpu, &hc, true);
2153
		break;
2154
	case HVCALL_SEND_IPI:
2155
		if (unlikely(hc.rep)) {
2156 2157 2158
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2159
		ret = kvm_hv_send_ipi(vcpu, &hc, false);
2160 2161
		break;
	case HVCALL_SEND_IPI_EX:
2162
		if (unlikely(hc.fast || hc.rep)) {
2163 2164 2165
			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
			break;
		}
2166
		ret = kvm_hv_send_ipi(vcpu, &hc, true);
2167
		break;
2168 2169
	case HVCALL_POST_DEBUG_DATA:
	case HVCALL_RETRIEVE_DEBUG_DATA:
2170
		if (unlikely(hc.fast)) {
2171 2172 2173 2174 2175
			ret = HV_STATUS_INVALID_PARAMETER;
			break;
		}
		fallthrough;
	case HVCALL_RESET_DEBUG_SESSION: {
2176
		struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

		if (!kvm_hv_is_syndbg_enabled(vcpu)) {
			ret = HV_STATUS_INVALID_HYPERCALL_CODE;
			break;
		}

		if (!(syndbg->options & HV_X64_SYNDBG_OPTION_USE_HCALLS)) {
			ret = HV_STATUS_OPERATION_DENIED;
			break;
		}
		vcpu->run->exit_reason = KVM_EXIT_HYPERV;
		vcpu->run->hyperv.type = KVM_EXIT_HYPERV_HCALL;
2189 2190 2191
		vcpu->run->hyperv.u.hcall.input = hc.param;
		vcpu->run->hyperv.u.hcall.params[0] = hc.ingpa;
		vcpu->run->hyperv.u.hcall.params[1] = hc.outgpa;
2192 2193 2194 2195
		vcpu->arch.complete_userspace_io =
				kvm_hv_hypercall_complete_userspace;
		return 0;
	}
2196
	default:
2197
		ret = HV_STATUS_INVALID_HYPERCALL_CODE;
2198 2199 2200
		break;
	}

2201
	return kvm_hv_hypercall_complete(vcpu, ret);
2202
}
2203 2204 2205

void kvm_hv_init_vm(struct kvm *kvm)
{
2206 2207 2208 2209
	struct kvm_hv *hv = to_kvm_hv(kvm);

	mutex_init(&hv->hv_lock);
	idr_init(&hv->conn_to_evt);
2210 2211 2212 2213
}

void kvm_hv_destroy_vm(struct kvm *kvm)
{
2214
	struct kvm_hv *hv = to_kvm_hv(kvm);
2215 2216 2217
	struct eventfd_ctx *eventfd;
	int i;

2218
	idr_for_each_entry(&hv->conn_to_evt, eventfd, i)
2219
		eventfd_ctx_put(eventfd);
2220
	idr_destroy(&hv->conn_to_evt);
2221 2222 2223 2224
}

static int kvm_hv_eventfd_assign(struct kvm *kvm, u32 conn_id, int fd)
{
2225
	struct kvm_hv *hv = to_kvm_hv(kvm);
2226 2227 2228 2229 2230 2231 2232 2233 2234
	struct eventfd_ctx *eventfd;
	int ret;

	eventfd = eventfd_ctx_fdget(fd);
	if (IS_ERR(eventfd))
		return PTR_ERR(eventfd);

	mutex_lock(&hv->hv_lock);
	ret = idr_alloc(&hv->conn_to_evt, eventfd, conn_id, conn_id + 1,
2235
			GFP_KERNEL_ACCOUNT);
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
	mutex_unlock(&hv->hv_lock);

	if (ret >= 0)
		return 0;

	if (ret == -ENOSPC)
		ret = -EEXIST;
	eventfd_ctx_put(eventfd);
	return ret;
}

static int kvm_hv_eventfd_deassign(struct kvm *kvm, u32 conn_id)
{
2249
	struct kvm_hv *hv = to_kvm_hv(kvm);
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
	struct eventfd_ctx *eventfd;

	mutex_lock(&hv->hv_lock);
	eventfd = idr_remove(&hv->conn_to_evt, conn_id);
	mutex_unlock(&hv->hv_lock);

	if (!eventfd)
		return -ENOENT;

	synchronize_srcu(&kvm->srcu);
	eventfd_ctx_put(eventfd);
	return 0;
}

int kvm_vm_ioctl_hv_eventfd(struct kvm *kvm, struct kvm_hyperv_eventfd *args)
{
	if ((args->flags & ~KVM_HYPERV_EVENTFD_DEASSIGN) ||
	    (args->conn_id & ~KVM_HYPERV_CONN_ID_MASK))
		return -EINVAL;

	if (args->flags == KVM_HYPERV_EVENTFD_DEASSIGN)
		return kvm_hv_eventfd_deassign(kvm, args->conn_id);
	return kvm_hv_eventfd_assign(kvm, args->conn_id, args->fd);
2273
}
2274

2275 2276
int kvm_get_hv_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid2 *cpuid,
		     struct kvm_cpuid_entry2 __user *entries)
2277
{
2278
	uint16_t evmcs_ver = 0;
2279 2280 2281 2282 2283 2284 2285
	struct kvm_cpuid_entry2 cpuid_entries[] = {
		{ .function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS },
		{ .function = HYPERV_CPUID_INTERFACE },
		{ .function = HYPERV_CPUID_VERSION },
		{ .function = HYPERV_CPUID_FEATURES },
		{ .function = HYPERV_CPUID_ENLIGHTMENT_INFO },
		{ .function = HYPERV_CPUID_IMPLEMENT_LIMITS },
2286 2287 2288
		{ .function = HYPERV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS },
		{ .function = HYPERV_CPUID_SYNDBG_INTERFACE },
		{ .function = HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES	},
2289 2290 2291 2292
		{ .function = HYPERV_CPUID_NESTED_FEATURES },
	};
	int i, nent = ARRAY_SIZE(cpuid_entries);

2293 2294
	if (kvm_x86_ops.nested_ops->get_evmcs_version)
		evmcs_ver = kvm_x86_ops.nested_ops->get_evmcs_version(vcpu);
2295

2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
	/* Skip NESTED_FEATURES if eVMCS is not supported */
	if (!evmcs_ver)
		--nent;

	if (cpuid->nent < nent)
		return -E2BIG;

	if (cpuid->nent > nent)
		cpuid->nent = nent;

	for (i = 0; i < nent; i++) {
		struct kvm_cpuid_entry2 *ent = &cpuid_entries[i];
		u32 signature[3];

		switch (ent->function) {
		case HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS:
			memcpy(signature, "Linux KVM Hv", 12);

2314
			ent->eax = HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES;
2315 2316 2317 2318 2319 2320
			ent->ebx = signature[0];
			ent->ecx = signature[1];
			ent->edx = signature[2];
			break;

		case HYPERV_CPUID_INTERFACE:
2321
			ent->eax = HYPERV_CPUID_SIGNATURE_EAX;
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
			break;

		case HYPERV_CPUID_VERSION:
			/*
			 * We implement some Hyper-V 2016 functions so let's use
			 * this version.
			 */
			ent->eax = 0x00003839;
			ent->ebx = 0x000A0000;
			break;

		case HYPERV_CPUID_FEATURES:
2334
			ent->eax |= HV_MSR_VP_RUNTIME_AVAILABLE;
2335
			ent->eax |= HV_MSR_TIME_REF_COUNT_AVAILABLE;
2336
			ent->eax |= HV_MSR_SYNIC_AVAILABLE;
2337
			ent->eax |= HV_MSR_SYNTIMER_AVAILABLE;
2338 2339 2340 2341
			ent->eax |= HV_MSR_APIC_ACCESS_AVAILABLE;
			ent->eax |= HV_MSR_HYPERCALL_AVAILABLE;
			ent->eax |= HV_MSR_VP_INDEX_AVAILABLE;
			ent->eax |= HV_MSR_RESET_AVAILABLE;
2342
			ent->eax |= HV_MSR_REFERENCE_TSC_AVAILABLE;
2343 2344
			ent->eax |= HV_ACCESS_FREQUENCY_MSRS;
			ent->eax |= HV_ACCESS_REENLIGHTENMENT;
2345

2346 2347
			ent->ebx |= HV_POST_MESSAGES;
			ent->ebx |= HV_SIGNAL_EVENTS;
2348

2349
			ent->edx |= HV_X64_HYPERCALL_XMM_INPUT_AVAILABLE;
2350 2351
			ent->edx |= HV_FEATURE_FREQUENCY_MSRS_AVAILABLE;
			ent->edx |= HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE;
2352

2353
			ent->ebx |= HV_DEBUGGING;
2354 2355 2356
			ent->edx |= HV_X64_GUEST_DEBUGGING_AVAILABLE;
			ent->edx |= HV_FEATURE_DEBUG_MSRS_AVAILABLE;

2357 2358 2359 2360
			/*
			 * Direct Synthetic timers only make sense with in-kernel
			 * LAPIC
			 */
2361
			if (!vcpu || lapic_in_kernel(vcpu))
2362
				ent->edx |= HV_STIMER_DIRECT_MODE_AVAILABLE;
2363 2364 2365 2366 2367 2368 2369 2370 2371

			break;

		case HYPERV_CPUID_ENLIGHTMENT_INFO:
			ent->eax |= HV_X64_REMOTE_TLB_FLUSH_RECOMMENDED;
			ent->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
			ent->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
			ent->eax |= HV_X64_CLUSTER_IPI_RECOMMENDED;
			ent->eax |= HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED;
2372 2373
			if (evmcs_ver)
				ent->eax |= HV_X64_ENLIGHTENED_VMCS_RECOMMENDED;
2374 2375
			if (!cpu_smt_possible())
				ent->eax |= HV_X64_NO_NONARCH_CORESHARING;
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
			/*
			 * Default number of spinlock retry attempts, matches
			 * HyperV 2016.
			 */
			ent->ebx = 0x00000FFF;

			break;

		case HYPERV_CPUID_IMPLEMENT_LIMITS:
			/* Maximum number of virtual processors */
			ent->eax = KVM_MAX_VCPUS;
			/*
			 * Maximum number of logical processors, matches
			 * HyperV 2016.
			 */
			ent->ebx = 64;

			break;

		case HYPERV_CPUID_NESTED_FEATURES:
			ent->eax = evmcs_ver;

			break;

2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
		case HYPERV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS:
			memcpy(signature, "Linux KVM Hv", 12);

			ent->eax = 0;
			ent->ebx = signature[0];
			ent->ecx = signature[1];
			ent->edx = signature[2];
			break;

		case HYPERV_CPUID_SYNDBG_INTERFACE:
			memcpy(signature, "VS#1\0\0\0\0\0\0\0\0", 12);
			ent->eax = signature[0];
			break;

		case HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES:
			ent->eax |= HV_X64_SYNDBG_CAP_ALLOW_KERNEL_DEBUGGING;
			break;

2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
		default:
			break;
		}
	}

	if (copy_to_user(entries, cpuid_entries,
			 nent * sizeof(struct kvm_cpuid_entry2)))
		return -EFAULT;

	return 0;
}