xref: /linux/arch/x86/kvm/hyperv.c (revision 73d7cf07109e79b093d1a1fb57a88d4048cd9b4b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * KVM Microsoft Hyper-V emulation
4  *
5  * derived from arch/x86/kvm/x86.c
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright (C) 2008 Qumranet, Inc.
9  * Copyright IBM Corporation, 2008
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  * Copyright (C) 2015 Andrey Smetanin <asmetanin@virtuozzo.com>
12  *
13  * Authors:
14  *   Avi Kivity   <avi@qumranet.com>
15  *   Yaniv Kamay  <yaniv@qumranet.com>
16  *   Amit Shah    <amit.shah@qumranet.com>
17  *   Ben-Ami Yassour <benami@il.ibm.com>
18  *   Andrey Smetanin <asmetanin@virtuozzo.com>
19  */
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21 
22 #include "x86.h"
23 #include "lapic.h"
24 #include "ioapic.h"
25 #include "cpuid.h"
26 #include "hyperv.h"
27 #include "mmu.h"
28 #include "xen.h"
29 
30 #include <linux/cpu.h>
31 #include <linux/kvm_host.h>
32 #include <linux/highmem.h>
33 #include <linux/sched/cputime.h>
34 #include <linux/spinlock.h>
35 #include <linux/eventfd.h>
36 
37 #include <asm/apicdef.h>
38 #include <asm/mshyperv.h>
39 #include <trace/events/kvm.h>
40 
41 #include "trace.h"
42 #include "irq.h"
43 #include "fpu.h"
44 
45 #define KVM_HV_MAX_SPARSE_VCPU_SET_BITS DIV_ROUND_UP(KVM_MAX_VCPUS, HV_VCPUS_PER_SPARSE_BANK)
46 
47 /*
48  * As per Hyper-V TLFS, extended hypercalls start from 0x8001
49  * (HvExtCallQueryCapabilities). Response of this hypercalls is a 64 bit value
50  * where each bit tells which extended hypercall is available besides
51  * HvExtCallQueryCapabilities.
52  *
53  * 0x8001 - First extended hypercall, HvExtCallQueryCapabilities, no bit
54  * assigned.
55  *
56  * 0x8002 - Bit 0
57  * 0x8003 - Bit 1
58  * ..
59  * 0x8041 - Bit 63
60  *
61  * Therefore, HV_EXT_CALL_MAX = 0x8001 + 64
62  */
63 #define HV_EXT_CALL_MAX (HV_EXT_CALL_QUERY_CAPABILITIES + 64)
64 
65 static void stimer_mark_pending(struct kvm_vcpu_hv_stimer *stimer,
66 				bool vcpu_kick);
67 
synic_read_sint(struct kvm_vcpu_hv_synic * synic,int sint)68 static inline u64 synic_read_sint(struct kvm_vcpu_hv_synic *synic, int sint)
69 {
70 	return atomic64_read(&synic->sint[sint]);
71 }
72 
synic_get_sint_vector(u64 sint_value)73 static inline int synic_get_sint_vector(u64 sint_value)
74 {
75 	if (sint_value & HV_SYNIC_SINT_MASKED)
76 		return -1;
77 	return sint_value & HV_SYNIC_SINT_VECTOR_MASK;
78 }
79 
synic_has_vector_connected(struct kvm_vcpu_hv_synic * synic,int vector)80 static bool synic_has_vector_connected(struct kvm_vcpu_hv_synic *synic,
81 				      int vector)
82 {
83 	int i;
84 
85 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
86 		if (synic_get_sint_vector(synic_read_sint(synic, i)) == vector)
87 			return true;
88 	}
89 	return false;
90 }
91 
synic_has_vector_auto_eoi(struct kvm_vcpu_hv_synic * synic,int vector)92 static bool synic_has_vector_auto_eoi(struct kvm_vcpu_hv_synic *synic,
93 				     int vector)
94 {
95 	int i;
96 	u64 sint_value;
97 
98 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
99 		sint_value = synic_read_sint(synic, i);
100 		if (synic_get_sint_vector(sint_value) == vector &&
101 		    sint_value & HV_SYNIC_SINT_AUTO_EOI)
102 			return true;
103 	}
104 	return false;
105 }
106 
synic_update_vector(struct kvm_vcpu_hv_synic * synic,int vector)107 static void synic_update_vector(struct kvm_vcpu_hv_synic *synic,
108 				int vector)
109 {
110 	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
111 	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
112 	bool auto_eoi_old, auto_eoi_new;
113 
114 	if (vector < HV_SYNIC_FIRST_VALID_VECTOR)
115 		return;
116 
117 	if (synic_has_vector_connected(synic, vector))
118 		__set_bit(vector, synic->vec_bitmap);
119 	else
120 		__clear_bit(vector, synic->vec_bitmap);
121 
122 	auto_eoi_old = !bitmap_empty(synic->auto_eoi_bitmap, 256);
123 
124 	if (synic_has_vector_auto_eoi(synic, vector))
125 		__set_bit(vector, synic->auto_eoi_bitmap);
126 	else
127 		__clear_bit(vector, synic->auto_eoi_bitmap);
128 
129 	auto_eoi_new = !bitmap_empty(synic->auto_eoi_bitmap, 256);
130 
131 	if (auto_eoi_old == auto_eoi_new)
132 		return;
133 
134 	if (!enable_apicv)
135 		return;
136 
137 	down_write(&vcpu->kvm->arch.apicv_update_lock);
138 
139 	if (auto_eoi_new)
140 		hv->synic_auto_eoi_used++;
141 	else
142 		hv->synic_auto_eoi_used--;
143 
144 	/*
145 	 * Inhibit APICv if any vCPU is using SynIC's AutoEOI, which relies on
146 	 * the hypervisor to manually inject IRQs.
147 	 */
148 	__kvm_set_or_clear_apicv_inhibit(vcpu->kvm,
149 					 APICV_INHIBIT_REASON_HYPERV,
150 					 !!hv->synic_auto_eoi_used);
151 
152 	up_write(&vcpu->kvm->arch.apicv_update_lock);
153 }
154 
synic_set_sint(struct kvm_vcpu_hv_synic * synic,int sint,u64 data,bool host)155 static int synic_set_sint(struct kvm_vcpu_hv_synic *synic, int sint,
156 			  u64 data, bool host)
157 {
158 	int vector, old_vector;
159 	bool masked;
160 
161 	vector = data & HV_SYNIC_SINT_VECTOR_MASK;
162 	masked = data & HV_SYNIC_SINT_MASKED;
163 
164 	/*
165 	 * Valid vectors are 16-255, however, nested Hyper-V attempts to write
166 	 * default '0x10000' value on boot and this should not #GP. We need to
167 	 * allow zero-initing the register from host as well.
168 	 */
169 	if (vector < HV_SYNIC_FIRST_VALID_VECTOR && !host && !masked)
170 		return 1;
171 	/*
172 	 * Guest may configure multiple SINTs to use the same vector, so
173 	 * we maintain a bitmap of vectors handled by synic, and a
174 	 * bitmap of vectors with auto-eoi behavior.  The bitmaps are
175 	 * updated here, and atomically queried on fast paths.
176 	 */
177 	old_vector = synic_read_sint(synic, sint) & HV_SYNIC_SINT_VECTOR_MASK;
178 
179 	atomic64_set(&synic->sint[sint], data);
180 
181 	synic_update_vector(synic, old_vector);
182 
183 	synic_update_vector(synic, vector);
184 
185 	/* Load SynIC vectors into EOI exit bitmap */
186 	kvm_make_request(KVM_REQ_SCAN_IOAPIC, hv_synic_to_vcpu(synic));
187 	return 0;
188 }
189 
get_vcpu_by_vpidx(struct kvm * kvm,u32 vpidx)190 static struct kvm_vcpu *get_vcpu_by_vpidx(struct kvm *kvm, u32 vpidx)
191 {
192 	struct kvm_vcpu *vcpu = NULL;
193 	unsigned long i;
194 
195 	if (vpidx >= KVM_MAX_VCPUS)
196 		return NULL;
197 
198 	vcpu = kvm_get_vcpu(kvm, vpidx);
199 	if (vcpu && kvm_hv_get_vpindex(vcpu) == vpidx)
200 		return vcpu;
201 	kvm_for_each_vcpu(i, vcpu, kvm)
202 		if (kvm_hv_get_vpindex(vcpu) == vpidx)
203 			return vcpu;
204 	return NULL;
205 }
206 
synic_get(struct kvm * kvm,u32 vpidx)207 static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)
208 {
209 	struct kvm_vcpu *vcpu;
210 	struct kvm_vcpu_hv_synic *synic;
211 
212 	vcpu = get_vcpu_by_vpidx(kvm, vpidx);
213 	if (!vcpu || !to_hv_vcpu(vcpu))
214 		return NULL;
215 	synic = to_hv_synic(vcpu);
216 	return (synic->active) ? synic : NULL;
217 }
218 
kvm_hv_notify_acked_sint(struct kvm_vcpu * vcpu,u32 sint)219 static void kvm_hv_notify_acked_sint(struct kvm_vcpu *vcpu, u32 sint)
220 {
221 	struct kvm *kvm = vcpu->kvm;
222 	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
223 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
224 	struct kvm_vcpu_hv_stimer *stimer;
225 	int gsi, idx;
226 
227 	trace_kvm_hv_notify_acked_sint(vcpu->vcpu_id, sint);
228 
229 	/* Try to deliver pending Hyper-V SynIC timers messages */
230 	for (idx = 0; idx < ARRAY_SIZE(hv_vcpu->stimer); idx++) {
231 		stimer = &hv_vcpu->stimer[idx];
232 		if (stimer->msg_pending && stimer->config.enable &&
233 		    !stimer->config.direct_mode &&
234 		    stimer->config.sintx == sint)
235 			stimer_mark_pending(stimer, false);
236 	}
237 
238 	idx = srcu_read_lock(&kvm->irq_srcu);
239 	gsi = atomic_read(&synic->sint_to_gsi[sint]);
240 	if (gsi != -1)
241 		kvm_notify_acked_gsi(kvm, gsi);
242 	srcu_read_unlock(&kvm->irq_srcu, idx);
243 }
244 
synic_exit(struct kvm_vcpu_hv_synic * synic,u32 msr)245 static void synic_exit(struct kvm_vcpu_hv_synic *synic, u32 msr)
246 {
247 	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
248 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
249 
250 	hv_vcpu->exit.type = KVM_EXIT_HYPERV_SYNIC;
251 	hv_vcpu->exit.u.synic.msr = msr;
252 	hv_vcpu->exit.u.synic.control = synic->control;
253 	hv_vcpu->exit.u.synic.evt_page = synic->evt_page;
254 	hv_vcpu->exit.u.synic.msg_page = synic->msg_page;
255 
256 	kvm_make_request(KVM_REQ_HV_EXIT, vcpu);
257 }
258 
synic_set_msr(struct kvm_vcpu_hv_synic * synic,u32 msr,u64 data,bool host)259 static int synic_set_msr(struct kvm_vcpu_hv_synic *synic,
260 			 u32 msr, u64 data, bool host)
261 {
262 	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
263 	int ret;
264 
265 	if (!synic->active && (!host || data))
266 		return 1;
267 
268 	trace_kvm_hv_synic_set_msr(vcpu->vcpu_id, msr, data, host);
269 
270 	ret = 0;
271 	switch (msr) {
272 	case HV_X64_MSR_SCONTROL:
273 		synic->control = data;
274 		if (!host)
275 			synic_exit(synic, msr);
276 		break;
277 	case HV_X64_MSR_SVERSION:
278 		if (!host) {
279 			ret = 1;
280 			break;
281 		}
282 		synic->version = data;
283 		break;
284 	case HV_X64_MSR_SIEFP:
285 		if ((data & HV_SYNIC_SIEFP_ENABLE) && !host &&
286 		    !synic->dont_zero_synic_pages)
287 			if (kvm_clear_guest(vcpu->kvm,
288 					    data & PAGE_MASK, PAGE_SIZE)) {
289 				ret = 1;
290 				break;
291 			}
292 		synic->evt_page = data;
293 		if (!host)
294 			synic_exit(synic, msr);
295 		break;
296 	case HV_X64_MSR_SIMP:
297 		if ((data & HV_SYNIC_SIMP_ENABLE) && !host &&
298 		    !synic->dont_zero_synic_pages)
299 			if (kvm_clear_guest(vcpu->kvm,
300 					    data & PAGE_MASK, PAGE_SIZE)) {
301 				ret = 1;
302 				break;
303 			}
304 		synic->msg_page = data;
305 		if (!host)
306 			synic_exit(synic, msr);
307 		break;
308 	case HV_X64_MSR_EOM: {
309 		int i;
310 
311 		if (!synic->active)
312 			break;
313 
314 		for (i = 0; i < ARRAY_SIZE(synic->sint); i++)
315 			kvm_hv_notify_acked_sint(vcpu, i);
316 		break;
317 	}
318 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
319 		ret = synic_set_sint(synic, msr - HV_X64_MSR_SINT0, data, host);
320 		break;
321 	default:
322 		ret = 1;
323 		break;
324 	}
325 	return ret;
326 }
327 
kvm_hv_is_syndbg_enabled(struct kvm_vcpu * vcpu)328 static bool kvm_hv_is_syndbg_enabled(struct kvm_vcpu *vcpu)
329 {
330 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
331 
332 	return hv_vcpu->cpuid_cache.syndbg_cap_eax &
333 		HV_X64_SYNDBG_CAP_ALLOW_KERNEL_DEBUGGING;
334 }
335 
kvm_hv_syndbg_complete_userspace(struct kvm_vcpu * vcpu)336 static int kvm_hv_syndbg_complete_userspace(struct kvm_vcpu *vcpu)
337 {
338 	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
339 
340 	if (vcpu->run->hyperv.u.syndbg.msr == HV_X64_MSR_SYNDBG_CONTROL)
341 		hv->hv_syndbg.control.status =
342 			vcpu->run->hyperv.u.syndbg.status;
343 	return 1;
344 }
345 
syndbg_exit(struct kvm_vcpu * vcpu,u32 msr)346 static void syndbg_exit(struct kvm_vcpu *vcpu, u32 msr)
347 {
348 	struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
349 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
350 
351 	hv_vcpu->exit.type = KVM_EXIT_HYPERV_SYNDBG;
352 	hv_vcpu->exit.u.syndbg.msr = msr;
353 	hv_vcpu->exit.u.syndbg.control = syndbg->control.control;
354 	hv_vcpu->exit.u.syndbg.send_page = syndbg->control.send_page;
355 	hv_vcpu->exit.u.syndbg.recv_page = syndbg->control.recv_page;
356 	hv_vcpu->exit.u.syndbg.pending_page = syndbg->control.pending_page;
357 	vcpu->arch.complete_userspace_io =
358 			kvm_hv_syndbg_complete_userspace;
359 
360 	kvm_make_request(KVM_REQ_HV_EXIT, vcpu);
361 }
362 
syndbg_set_msr(struct kvm_vcpu * vcpu,u32 msr,u64 data,bool host)363 static int syndbg_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
364 {
365 	struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
366 
367 	if (!kvm_hv_is_syndbg_enabled(vcpu) && !host)
368 		return 1;
369 
370 	trace_kvm_hv_syndbg_set_msr(vcpu->vcpu_id,
371 				    to_hv_vcpu(vcpu)->vp_index, msr, data);
372 	switch (msr) {
373 	case HV_X64_MSR_SYNDBG_CONTROL:
374 		syndbg->control.control = data;
375 		if (!host)
376 			syndbg_exit(vcpu, msr);
377 		break;
378 	case HV_X64_MSR_SYNDBG_STATUS:
379 		syndbg->control.status = data;
380 		break;
381 	case HV_X64_MSR_SYNDBG_SEND_BUFFER:
382 		syndbg->control.send_page = data;
383 		break;
384 	case HV_X64_MSR_SYNDBG_RECV_BUFFER:
385 		syndbg->control.recv_page = data;
386 		break;
387 	case HV_X64_MSR_SYNDBG_PENDING_BUFFER:
388 		syndbg->control.pending_page = data;
389 		if (!host)
390 			syndbg_exit(vcpu, msr);
391 		break;
392 	case HV_X64_MSR_SYNDBG_OPTIONS:
393 		syndbg->options = data;
394 		break;
395 	default:
396 		break;
397 	}
398 
399 	return 0;
400 }
401 
syndbg_get_msr(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)402 static int syndbg_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
403 {
404 	struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
405 
406 	if (!kvm_hv_is_syndbg_enabled(vcpu) && !host)
407 		return 1;
408 
409 	switch (msr) {
410 	case HV_X64_MSR_SYNDBG_CONTROL:
411 		*pdata = syndbg->control.control;
412 		break;
413 	case HV_X64_MSR_SYNDBG_STATUS:
414 		*pdata = syndbg->control.status;
415 		break;
416 	case HV_X64_MSR_SYNDBG_SEND_BUFFER:
417 		*pdata = syndbg->control.send_page;
418 		break;
419 	case HV_X64_MSR_SYNDBG_RECV_BUFFER:
420 		*pdata = syndbg->control.recv_page;
421 		break;
422 	case HV_X64_MSR_SYNDBG_PENDING_BUFFER:
423 		*pdata = syndbg->control.pending_page;
424 		break;
425 	case HV_X64_MSR_SYNDBG_OPTIONS:
426 		*pdata = syndbg->options;
427 		break;
428 	default:
429 		break;
430 	}
431 
432 	trace_kvm_hv_syndbg_get_msr(vcpu->vcpu_id, kvm_hv_get_vpindex(vcpu), msr, *pdata);
433 
434 	return 0;
435 }
436 
synic_get_msr(struct kvm_vcpu_hv_synic * synic,u32 msr,u64 * pdata,bool host)437 static int synic_get_msr(struct kvm_vcpu_hv_synic *synic, u32 msr, u64 *pdata,
438 			 bool host)
439 {
440 	int ret;
441 
442 	if (!synic->active && !host)
443 		return 1;
444 
445 	ret = 0;
446 	switch (msr) {
447 	case HV_X64_MSR_SCONTROL:
448 		*pdata = synic->control;
449 		break;
450 	case HV_X64_MSR_SVERSION:
451 		*pdata = synic->version;
452 		break;
453 	case HV_X64_MSR_SIEFP:
454 		*pdata = synic->evt_page;
455 		break;
456 	case HV_X64_MSR_SIMP:
457 		*pdata = synic->msg_page;
458 		break;
459 	case HV_X64_MSR_EOM:
460 		*pdata = 0;
461 		break;
462 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
463 		*pdata = atomic64_read(&synic->sint[msr - HV_X64_MSR_SINT0]);
464 		break;
465 	default:
466 		ret = 1;
467 		break;
468 	}
469 	return ret;
470 }
471 
synic_set_irq(struct kvm_vcpu_hv_synic * synic,u32 sint)472 static int synic_set_irq(struct kvm_vcpu_hv_synic *synic, u32 sint)
473 {
474 	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
475 	struct kvm_lapic_irq irq;
476 	int ret, vector;
477 
478 	if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
479 		return -EINVAL;
480 
481 	if (sint >= ARRAY_SIZE(synic->sint))
482 		return -EINVAL;
483 
484 	vector = synic_get_sint_vector(synic_read_sint(synic, sint));
485 	if (vector < 0)
486 		return -ENOENT;
487 
488 	memset(&irq, 0, sizeof(irq));
489 	irq.shorthand = APIC_DEST_SELF;
490 	irq.dest_mode = APIC_DEST_PHYSICAL;
491 	irq.delivery_mode = APIC_DM_FIXED;
492 	irq.vector = vector;
493 	irq.level = 1;
494 
495 	ret = kvm_irq_delivery_to_apic(vcpu->kvm, vcpu->arch.apic, &irq, NULL);
496 	trace_kvm_hv_synic_set_irq(vcpu->vcpu_id, sint, irq.vector, ret);
497 	return ret;
498 }
499 
kvm_hv_synic_set_irq(struct kvm * kvm,u32 vpidx,u32 sint)500 int kvm_hv_synic_set_irq(struct kvm *kvm, u32 vpidx, u32 sint)
501 {
502 	struct kvm_vcpu_hv_synic *synic;
503 
504 	synic = synic_get(kvm, vpidx);
505 	if (!synic)
506 		return -EINVAL;
507 
508 	return synic_set_irq(synic, sint);
509 }
510 
kvm_hv_synic_send_eoi(struct kvm_vcpu * vcpu,int vector)511 void kvm_hv_synic_send_eoi(struct kvm_vcpu *vcpu, int vector)
512 {
513 	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
514 	int i;
515 
516 	trace_kvm_hv_synic_send_eoi(vcpu->vcpu_id, vector);
517 
518 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++)
519 		if (synic_get_sint_vector(synic_read_sint(synic, i)) == vector)
520 			kvm_hv_notify_acked_sint(vcpu, i);
521 }
522 
kvm_hv_set_sint_gsi(struct kvm * kvm,u32 vpidx,u32 sint,int gsi)523 static int kvm_hv_set_sint_gsi(struct kvm *kvm, u32 vpidx, u32 sint, int gsi)
524 {
525 	struct kvm_vcpu_hv_synic *synic;
526 
527 	synic = synic_get(kvm, vpidx);
528 	if (!synic)
529 		return -EINVAL;
530 
531 	if (sint >= ARRAY_SIZE(synic->sint_to_gsi))
532 		return -EINVAL;
533 
534 	atomic_set(&synic->sint_to_gsi[sint], gsi);
535 	return 0;
536 }
537 
kvm_hv_irq_routing_update(struct kvm * kvm)538 void kvm_hv_irq_routing_update(struct kvm *kvm)
539 {
540 	struct kvm_irq_routing_table *irq_rt;
541 	struct kvm_kernel_irq_routing_entry *e;
542 	u32 gsi;
543 
544 	irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu,
545 					lockdep_is_held(&kvm->irq_lock));
546 
547 	for (gsi = 0; gsi < irq_rt->nr_rt_entries; gsi++) {
548 		hlist_for_each_entry(e, &irq_rt->map[gsi], link) {
549 			if (e->type == KVM_IRQ_ROUTING_HV_SINT)
550 				kvm_hv_set_sint_gsi(kvm, e->hv_sint.vcpu,
551 						    e->hv_sint.sint, gsi);
552 		}
553 	}
554 }
555 
synic_init(struct kvm_vcpu_hv_synic * synic)556 static void synic_init(struct kvm_vcpu_hv_synic *synic)
557 {
558 	int i;
559 
560 	memset(synic, 0, sizeof(*synic));
561 	synic->version = HV_SYNIC_VERSION_1;
562 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
563 		atomic64_set(&synic->sint[i], HV_SYNIC_SINT_MASKED);
564 		atomic_set(&synic->sint_to_gsi[i], -1);
565 	}
566 }
567 
get_time_ref_counter(struct kvm * kvm)568 static u64 get_time_ref_counter(struct kvm *kvm)
569 {
570 	struct kvm_hv *hv = to_kvm_hv(kvm);
571 	struct kvm_vcpu *vcpu;
572 	u64 tsc;
573 
574 	/*
575 	 * Fall back to get_kvmclock_ns() when TSC page hasn't been set up,
576 	 * is broken, disabled or being updated.
577 	 */
578 	if (hv->hv_tsc_page_status != HV_TSC_PAGE_SET)
579 		return div_u64(get_kvmclock_ns(kvm), 100);
580 
581 	vcpu = kvm_get_vcpu(kvm, 0);
582 	tsc = kvm_read_l1_tsc(vcpu, rdtsc());
583 	return mul_u64_u64_shr(tsc, hv->tsc_ref.tsc_scale, 64)
584 		+ hv->tsc_ref.tsc_offset;
585 }
586 
stimer_mark_pending(struct kvm_vcpu_hv_stimer * stimer,bool vcpu_kick)587 static void stimer_mark_pending(struct kvm_vcpu_hv_stimer *stimer,
588 				bool vcpu_kick)
589 {
590 	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
591 
592 	set_bit(stimer->index,
593 		to_hv_vcpu(vcpu)->stimer_pending_bitmap);
594 	kvm_make_request(KVM_REQ_HV_STIMER, vcpu);
595 	if (vcpu_kick)
596 		kvm_vcpu_kick(vcpu);
597 }
598 
stimer_cleanup(struct kvm_vcpu_hv_stimer * stimer)599 static void stimer_cleanup(struct kvm_vcpu_hv_stimer *stimer)
600 {
601 	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
602 
603 	trace_kvm_hv_stimer_cleanup(hv_stimer_to_vcpu(stimer)->vcpu_id,
604 				    stimer->index);
605 
606 	hrtimer_cancel(&stimer->timer);
607 	clear_bit(stimer->index,
608 		  to_hv_vcpu(vcpu)->stimer_pending_bitmap);
609 	stimer->msg_pending = false;
610 	stimer->exp_time = 0;
611 }
612 
stimer_timer_callback(struct hrtimer * timer)613 static enum hrtimer_restart stimer_timer_callback(struct hrtimer *timer)
614 {
615 	struct kvm_vcpu_hv_stimer *stimer;
616 
617 	stimer = container_of(timer, struct kvm_vcpu_hv_stimer, timer);
618 	trace_kvm_hv_stimer_callback(hv_stimer_to_vcpu(stimer)->vcpu_id,
619 				     stimer->index);
620 	stimer_mark_pending(stimer, true);
621 
622 	return HRTIMER_NORESTART;
623 }
624 
625 /*
626  * stimer_start() assumptions:
627  * a) stimer->count is not equal to 0
628  * b) stimer->config has HV_STIMER_ENABLE flag
629  */
stimer_start(struct kvm_vcpu_hv_stimer * stimer)630 static int stimer_start(struct kvm_vcpu_hv_stimer *stimer)
631 {
632 	u64 time_now;
633 	ktime_t ktime_now;
634 
635 	time_now = get_time_ref_counter(hv_stimer_to_vcpu(stimer)->kvm);
636 	ktime_now = ktime_get();
637 
638 	if (stimer->config.periodic) {
639 		if (stimer->exp_time) {
640 			if (time_now >= stimer->exp_time) {
641 				u64 remainder;
642 
643 				div64_u64_rem(time_now - stimer->exp_time,
644 					      stimer->count, &remainder);
645 				stimer->exp_time =
646 					time_now + (stimer->count - remainder);
647 			}
648 		} else
649 			stimer->exp_time = time_now + stimer->count;
650 
651 		trace_kvm_hv_stimer_start_periodic(
652 					hv_stimer_to_vcpu(stimer)->vcpu_id,
653 					stimer->index,
654 					time_now, stimer->exp_time);
655 
656 		hrtimer_start(&stimer->timer,
657 			      ktime_add_ns(ktime_now,
658 					   100 * (stimer->exp_time - time_now)),
659 			      HRTIMER_MODE_ABS);
660 		return 0;
661 	}
662 	stimer->exp_time = stimer->count;
663 	if (time_now >= stimer->count) {
664 		/*
665 		 * Expire timer according to Hypervisor Top-Level Functional
666 		 * specification v4(15.3.1):
667 		 * "If a one shot is enabled and the specified count is in
668 		 * the past, it will expire immediately."
669 		 */
670 		stimer_mark_pending(stimer, false);
671 		return 0;
672 	}
673 
674 	trace_kvm_hv_stimer_start_one_shot(hv_stimer_to_vcpu(stimer)->vcpu_id,
675 					   stimer->index,
676 					   time_now, stimer->count);
677 
678 	hrtimer_start(&stimer->timer,
679 		      ktime_add_ns(ktime_now, 100 * (stimer->count - time_now)),
680 		      HRTIMER_MODE_ABS);
681 	return 0;
682 }
683 
stimer_set_config(struct kvm_vcpu_hv_stimer * stimer,u64 config,bool host)684 static int stimer_set_config(struct kvm_vcpu_hv_stimer *stimer, u64 config,
685 			     bool host)
686 {
687 	union hv_stimer_config new_config = {.as_uint64 = config},
688 		old_config = {.as_uint64 = stimer->config.as_uint64};
689 	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
690 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
691 	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
692 
693 	if (!synic->active && (!host || config))
694 		return 1;
695 
696 	if (unlikely(!host && hv_vcpu->enforce_cpuid && new_config.direct_mode &&
697 		     !(hv_vcpu->cpuid_cache.features_edx &
698 		       HV_STIMER_DIRECT_MODE_AVAILABLE)))
699 		return 1;
700 
701 	trace_kvm_hv_stimer_set_config(hv_stimer_to_vcpu(stimer)->vcpu_id,
702 				       stimer->index, config, host);
703 
704 	stimer_cleanup(stimer);
705 	if (old_config.enable &&
706 	    !new_config.direct_mode && new_config.sintx == 0)
707 		new_config.enable = 0;
708 	stimer->config.as_uint64 = new_config.as_uint64;
709 
710 	if (stimer->config.enable)
711 		stimer_mark_pending(stimer, false);
712 
713 	return 0;
714 }
715 
stimer_set_count(struct kvm_vcpu_hv_stimer * stimer,u64 count,bool host)716 static int stimer_set_count(struct kvm_vcpu_hv_stimer *stimer, u64 count,
717 			    bool host)
718 {
719 	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
720 	struct kvm_vcpu_hv_synic *synic = to_hv_synic(vcpu);
721 
722 	if (!synic->active && (!host || count))
723 		return 1;
724 
725 	trace_kvm_hv_stimer_set_count(hv_stimer_to_vcpu(stimer)->vcpu_id,
726 				      stimer->index, count, host);
727 
728 	stimer_cleanup(stimer);
729 	stimer->count = count;
730 	if (!host) {
731 		if (stimer->count == 0)
732 			stimer->config.enable = 0;
733 		else if (stimer->config.auto_enable)
734 			stimer->config.enable = 1;
735 	}
736 
737 	if (stimer->config.enable)
738 		stimer_mark_pending(stimer, false);
739 
740 	return 0;
741 }
742 
stimer_get_config(struct kvm_vcpu_hv_stimer * stimer,u64 * pconfig)743 static int stimer_get_config(struct kvm_vcpu_hv_stimer *stimer, u64 *pconfig)
744 {
745 	*pconfig = stimer->config.as_uint64;
746 	return 0;
747 }
748 
stimer_get_count(struct kvm_vcpu_hv_stimer * stimer,u64 * pcount)749 static int stimer_get_count(struct kvm_vcpu_hv_stimer *stimer, u64 *pcount)
750 {
751 	*pcount = stimer->count;
752 	return 0;
753 }
754 
synic_deliver_msg(struct kvm_vcpu_hv_synic * synic,u32 sint,struct hv_message * src_msg,bool no_retry)755 static int synic_deliver_msg(struct kvm_vcpu_hv_synic *synic, u32 sint,
756 			     struct hv_message *src_msg, bool no_retry)
757 {
758 	struct kvm_vcpu *vcpu = hv_synic_to_vcpu(synic);
759 	int msg_off = offsetof(struct hv_message_page, sint_message[sint]);
760 	gfn_t msg_page_gfn;
761 	struct hv_message_header hv_hdr;
762 	int r;
763 
764 	if (!(synic->msg_page & HV_SYNIC_SIMP_ENABLE))
765 		return -ENOENT;
766 
767 	msg_page_gfn = synic->msg_page >> PAGE_SHIFT;
768 
769 	/*
770 	 * Strictly following the spec-mandated ordering would assume setting
771 	 * .msg_pending before checking .message_type.  However, this function
772 	 * is only called in vcpu context so the entire update is atomic from
773 	 * guest POV and thus the exact order here doesn't matter.
774 	 */
775 	r = kvm_vcpu_read_guest_page(vcpu, msg_page_gfn, &hv_hdr.message_type,
776 				     msg_off + offsetof(struct hv_message,
777 							header.message_type),
778 				     sizeof(hv_hdr.message_type));
779 	if (r < 0)
780 		return r;
781 
782 	if (hv_hdr.message_type != HVMSG_NONE) {
783 		if (no_retry)
784 			return 0;
785 
786 		hv_hdr.message_flags.msg_pending = 1;
787 		r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn,
788 					      &hv_hdr.message_flags,
789 					      msg_off +
790 					      offsetof(struct hv_message,
791 						       header.message_flags),
792 					      sizeof(hv_hdr.message_flags));
793 		if (r < 0)
794 			return r;
795 		return -EAGAIN;
796 	}
797 
798 	r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn, src_msg, msg_off,
799 				      sizeof(src_msg->header) +
800 				      src_msg->header.payload_size);
801 	if (r < 0)
802 		return r;
803 
804 	r = synic_set_irq(synic, sint);
805 	if (r < 0)
806 		return r;
807 	if (r == 0)
808 		return -EFAULT;
809 	return 0;
810 }
811 
stimer_send_msg(struct kvm_vcpu_hv_stimer * stimer)812 static int stimer_send_msg(struct kvm_vcpu_hv_stimer *stimer)
813 {
814 	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
815 	struct hv_message *msg = &stimer->msg;
816 	struct hv_timer_message_payload *payload =
817 			(struct hv_timer_message_payload *)&msg->u.payload;
818 
819 	/*
820 	 * To avoid piling up periodic ticks, don't retry message
821 	 * delivery for them (within "lazy" lost ticks policy).
822 	 */
823 	bool no_retry = stimer->config.periodic;
824 
825 	payload->expiration_time = stimer->exp_time;
826 	payload->delivery_time = get_time_ref_counter(vcpu->kvm);
827 	return synic_deliver_msg(to_hv_synic(vcpu),
828 				 stimer->config.sintx, msg,
829 				 no_retry);
830 }
831 
stimer_notify_direct(struct kvm_vcpu_hv_stimer * stimer)832 static int stimer_notify_direct(struct kvm_vcpu_hv_stimer *stimer)
833 {
834 	struct kvm_vcpu *vcpu = hv_stimer_to_vcpu(stimer);
835 	struct kvm_lapic_irq irq = {
836 		.delivery_mode = APIC_DM_FIXED,
837 		.vector = stimer->config.apic_vector
838 	};
839 
840 	if (lapic_in_kernel(vcpu))
841 		return !kvm_apic_set_irq(vcpu, &irq, NULL);
842 	return 0;
843 }
844 
stimer_expiration(struct kvm_vcpu_hv_stimer * stimer)845 static void stimer_expiration(struct kvm_vcpu_hv_stimer *stimer)
846 {
847 	int r, direct = stimer->config.direct_mode;
848 
849 	stimer->msg_pending = true;
850 	if (!direct)
851 		r = stimer_send_msg(stimer);
852 	else
853 		r = stimer_notify_direct(stimer);
854 	trace_kvm_hv_stimer_expiration(hv_stimer_to_vcpu(stimer)->vcpu_id,
855 				       stimer->index, direct, r);
856 	if (!r) {
857 		stimer->msg_pending = false;
858 		if (!(stimer->config.periodic))
859 			stimer->config.enable = 0;
860 	}
861 }
862 
kvm_hv_process_stimers(struct kvm_vcpu * vcpu)863 void kvm_hv_process_stimers(struct kvm_vcpu *vcpu)
864 {
865 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
866 	struct kvm_vcpu_hv_stimer *stimer;
867 	u64 time_now, exp_time;
868 	int i;
869 
870 	if (!hv_vcpu)
871 		return;
872 
873 	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
874 		if (test_and_clear_bit(i, hv_vcpu->stimer_pending_bitmap)) {
875 			stimer = &hv_vcpu->stimer[i];
876 			if (stimer->config.enable) {
877 				exp_time = stimer->exp_time;
878 
879 				if (exp_time) {
880 					time_now =
881 						get_time_ref_counter(vcpu->kvm);
882 					if (time_now >= exp_time)
883 						stimer_expiration(stimer);
884 				}
885 
886 				if ((stimer->config.enable) &&
887 				    stimer->count) {
888 					if (!stimer->msg_pending)
889 						stimer_start(stimer);
890 				} else
891 					stimer_cleanup(stimer);
892 			}
893 		}
894 }
895 
kvm_hv_vcpu_uninit(struct kvm_vcpu * vcpu)896 void kvm_hv_vcpu_uninit(struct kvm_vcpu *vcpu)
897 {
898 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
899 	int i;
900 
901 	if (!hv_vcpu)
902 		return;
903 
904 	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
905 		stimer_cleanup(&hv_vcpu->stimer[i]);
906 
907 	kfree(hv_vcpu);
908 	vcpu->arch.hyperv = NULL;
909 }
910 
kvm_hv_assist_page_enabled(struct kvm_vcpu * vcpu)911 bool kvm_hv_assist_page_enabled(struct kvm_vcpu *vcpu)
912 {
913 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
914 
915 	if (!hv_vcpu)
916 		return false;
917 
918 	if (!(hv_vcpu->hv_vapic & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE))
919 		return false;
920 	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
921 }
922 EXPORT_SYMBOL_GPL(kvm_hv_assist_page_enabled);
923 
kvm_hv_get_assist_page(struct kvm_vcpu * vcpu)924 int kvm_hv_get_assist_page(struct kvm_vcpu *vcpu)
925 {
926 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
927 
928 	if (!hv_vcpu || !kvm_hv_assist_page_enabled(vcpu))
929 		return -EFAULT;
930 
931 	return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data,
932 				     &hv_vcpu->vp_assist_page, sizeof(struct hv_vp_assist_page));
933 }
934 EXPORT_SYMBOL_GPL(kvm_hv_get_assist_page);
935 
stimer_prepare_msg(struct kvm_vcpu_hv_stimer * stimer)936 static void stimer_prepare_msg(struct kvm_vcpu_hv_stimer *stimer)
937 {
938 	struct hv_message *msg = &stimer->msg;
939 	struct hv_timer_message_payload *payload =
940 			(struct hv_timer_message_payload *)&msg->u.payload;
941 
942 	memset(&msg->header, 0, sizeof(msg->header));
943 	msg->header.message_type = HVMSG_TIMER_EXPIRED;
944 	msg->header.payload_size = sizeof(*payload);
945 
946 	payload->timer_index = stimer->index;
947 	payload->expiration_time = 0;
948 	payload->delivery_time = 0;
949 }
950 
stimer_init(struct kvm_vcpu_hv_stimer * stimer,int timer_index)951 static void stimer_init(struct kvm_vcpu_hv_stimer *stimer, int timer_index)
952 {
953 	memset(stimer, 0, sizeof(*stimer));
954 	stimer->index = timer_index;
955 	hrtimer_setup(&stimer->timer, stimer_timer_callback, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
956 	stimer_prepare_msg(stimer);
957 }
958 
kvm_hv_vcpu_init(struct kvm_vcpu * vcpu)959 int kvm_hv_vcpu_init(struct kvm_vcpu *vcpu)
960 {
961 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
962 	int i;
963 
964 	if (hv_vcpu)
965 		return 0;
966 
967 	hv_vcpu = kzalloc(sizeof(struct kvm_vcpu_hv), GFP_KERNEL_ACCOUNT);
968 	if (!hv_vcpu)
969 		return -ENOMEM;
970 
971 	vcpu->arch.hyperv = hv_vcpu;
972 	hv_vcpu->vcpu = vcpu;
973 
974 	synic_init(&hv_vcpu->synic);
975 
976 	bitmap_zero(hv_vcpu->stimer_pending_bitmap, HV_SYNIC_STIMER_COUNT);
977 	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
978 		stimer_init(&hv_vcpu->stimer[i], i);
979 
980 	hv_vcpu->vp_index = vcpu->vcpu_idx;
981 
982 	for (i = 0; i < HV_NR_TLB_FLUSH_FIFOS; i++) {
983 		INIT_KFIFO(hv_vcpu->tlb_flush_fifo[i].entries);
984 		spin_lock_init(&hv_vcpu->tlb_flush_fifo[i].write_lock);
985 	}
986 
987 	return 0;
988 }
989 
kvm_hv_activate_synic(struct kvm_vcpu * vcpu,bool dont_zero_synic_pages)990 int kvm_hv_activate_synic(struct kvm_vcpu *vcpu, bool dont_zero_synic_pages)
991 {
992 	struct kvm_vcpu_hv_synic *synic;
993 	int r;
994 
995 	r = kvm_hv_vcpu_init(vcpu);
996 	if (r)
997 		return r;
998 
999 	synic = to_hv_synic(vcpu);
1000 
1001 	synic->active = true;
1002 	synic->dont_zero_synic_pages = dont_zero_synic_pages;
1003 	synic->control = HV_SYNIC_CONTROL_ENABLE;
1004 	return 0;
1005 }
1006 
kvm_hv_msr_partition_wide(u32 msr)1007 static bool kvm_hv_msr_partition_wide(u32 msr)
1008 {
1009 	bool r = false;
1010 
1011 	switch (msr) {
1012 	case HV_X64_MSR_GUEST_OS_ID:
1013 	case HV_X64_MSR_HYPERCALL:
1014 	case HV_X64_MSR_REFERENCE_TSC:
1015 	case HV_X64_MSR_TIME_REF_COUNT:
1016 	case HV_X64_MSR_CRASH_CTL:
1017 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1018 	case HV_X64_MSR_RESET:
1019 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1020 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
1021 	case HV_X64_MSR_TSC_EMULATION_STATUS:
1022 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
1023 	case HV_X64_MSR_SYNDBG_OPTIONS:
1024 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
1025 		r = true;
1026 		break;
1027 	}
1028 
1029 	return r;
1030 }
1031 
kvm_hv_msr_get_crash_data(struct kvm * kvm,u32 index,u64 * pdata)1032 static int kvm_hv_msr_get_crash_data(struct kvm *kvm, u32 index, u64 *pdata)
1033 {
1034 	struct kvm_hv *hv = to_kvm_hv(kvm);
1035 	size_t size = ARRAY_SIZE(hv->hv_crash_param);
1036 
1037 	if (WARN_ON_ONCE(index >= size))
1038 		return -EINVAL;
1039 
1040 	*pdata = hv->hv_crash_param[array_index_nospec(index, size)];
1041 	return 0;
1042 }
1043 
kvm_hv_msr_get_crash_ctl(struct kvm * kvm,u64 * pdata)1044 static int kvm_hv_msr_get_crash_ctl(struct kvm *kvm, u64 *pdata)
1045 {
1046 	struct kvm_hv *hv = to_kvm_hv(kvm);
1047 
1048 	*pdata = hv->hv_crash_ctl;
1049 	return 0;
1050 }
1051 
kvm_hv_msr_set_crash_ctl(struct kvm * kvm,u64 data)1052 static int kvm_hv_msr_set_crash_ctl(struct kvm *kvm, u64 data)
1053 {
1054 	struct kvm_hv *hv = to_kvm_hv(kvm);
1055 
1056 	hv->hv_crash_ctl = data & HV_CRASH_CTL_CRASH_NOTIFY;
1057 
1058 	return 0;
1059 }
1060 
kvm_hv_msr_set_crash_data(struct kvm * kvm,u32 index,u64 data)1061 static int kvm_hv_msr_set_crash_data(struct kvm *kvm, u32 index, u64 data)
1062 {
1063 	struct kvm_hv *hv = to_kvm_hv(kvm);
1064 	size_t size = ARRAY_SIZE(hv->hv_crash_param);
1065 
1066 	if (WARN_ON_ONCE(index >= size))
1067 		return -EINVAL;
1068 
1069 	hv->hv_crash_param[array_index_nospec(index, size)] = data;
1070 	return 0;
1071 }
1072 
1073 /*
1074  * The kvmclock and Hyper-V TSC page use similar formulas, and converting
1075  * between them is possible:
1076  *
1077  * kvmclock formula:
1078  *    nsec = (ticks - tsc_timestamp) * tsc_to_system_mul * 2^(tsc_shift-32)
1079  *           + system_time
1080  *
1081  * Hyper-V formula:
1082  *    nsec/100 = ticks * scale / 2^64 + offset
1083  *
1084  * When tsc_timestamp = system_time = 0, offset is zero in the Hyper-V formula.
1085  * By dividing the kvmclock formula by 100 and equating what's left we get:
1086  *    ticks * scale / 2^64 = ticks * tsc_to_system_mul * 2^(tsc_shift-32) / 100
1087  *            scale / 2^64 =         tsc_to_system_mul * 2^(tsc_shift-32) / 100
1088  *            scale        =         tsc_to_system_mul * 2^(32+tsc_shift) / 100
1089  *
1090  * Now expand the kvmclock formula and divide by 100:
1091  *    nsec = ticks * tsc_to_system_mul * 2^(tsc_shift-32)
1092  *           - tsc_timestamp * tsc_to_system_mul * 2^(tsc_shift-32)
1093  *           + system_time
1094  *    nsec/100 = ticks * tsc_to_system_mul * 2^(tsc_shift-32) / 100
1095  *               - tsc_timestamp * tsc_to_system_mul * 2^(tsc_shift-32) / 100
1096  *               + system_time / 100
1097  *
1098  * Replace tsc_to_system_mul * 2^(tsc_shift-32) / 100 by scale / 2^64:
1099  *    nsec/100 = ticks * scale / 2^64
1100  *               - tsc_timestamp * scale / 2^64
1101  *               + system_time / 100
1102  *
1103  * Equate with the Hyper-V formula so that ticks * scale / 2^64 cancels out:
1104  *    offset = system_time / 100 - tsc_timestamp * scale / 2^64
1105  *
1106  * These two equivalencies are implemented in this function.
1107  */
compute_tsc_page_parameters(struct pvclock_vcpu_time_info * hv_clock,struct ms_hyperv_tsc_page * tsc_ref)1108 static bool compute_tsc_page_parameters(struct pvclock_vcpu_time_info *hv_clock,
1109 					struct ms_hyperv_tsc_page *tsc_ref)
1110 {
1111 	u64 max_mul;
1112 
1113 	if (!(hv_clock->flags & PVCLOCK_TSC_STABLE_BIT))
1114 		return false;
1115 
1116 	/*
1117 	 * check if scale would overflow, if so we use the time ref counter
1118 	 *    tsc_to_system_mul * 2^(tsc_shift+32) / 100 >= 2^64
1119 	 *    tsc_to_system_mul / 100 >= 2^(32-tsc_shift)
1120 	 *    tsc_to_system_mul >= 100 * 2^(32-tsc_shift)
1121 	 */
1122 	max_mul = 100ull << (32 - hv_clock->tsc_shift);
1123 	if (hv_clock->tsc_to_system_mul >= max_mul)
1124 		return false;
1125 
1126 	/*
1127 	 * Otherwise compute the scale and offset according to the formulas
1128 	 * derived above.
1129 	 */
1130 	tsc_ref->tsc_scale =
1131 		mul_u64_u32_div(1ULL << (32 + hv_clock->tsc_shift),
1132 				hv_clock->tsc_to_system_mul,
1133 				100);
1134 
1135 	tsc_ref->tsc_offset = hv_clock->system_time;
1136 	do_div(tsc_ref->tsc_offset, 100);
1137 	tsc_ref->tsc_offset -=
1138 		mul_u64_u64_shr(hv_clock->tsc_timestamp, tsc_ref->tsc_scale, 64);
1139 	return true;
1140 }
1141 
1142 /*
1143  * Don't touch TSC page values if the guest has opted for TSC emulation after
1144  * migration. KVM doesn't fully support reenlightenment notifications and TSC
1145  * access emulation and Hyper-V is known to expect the values in TSC page to
1146  * stay constant before TSC access emulation is disabled from guest side
1147  * (HV_X64_MSR_TSC_EMULATION_STATUS). KVM userspace is expected to preserve TSC
1148  * frequency and guest visible TSC value across migration (and prevent it when
1149  * TSC scaling is unsupported).
1150  */
tsc_page_update_unsafe(struct kvm_hv * hv)1151 static inline bool tsc_page_update_unsafe(struct kvm_hv *hv)
1152 {
1153 	return (hv->hv_tsc_page_status != HV_TSC_PAGE_GUEST_CHANGED) &&
1154 		hv->hv_tsc_emulation_control;
1155 }
1156 
kvm_hv_setup_tsc_page(struct kvm * kvm,struct pvclock_vcpu_time_info * hv_clock)1157 void kvm_hv_setup_tsc_page(struct kvm *kvm,
1158 			   struct pvclock_vcpu_time_info *hv_clock)
1159 {
1160 	struct kvm_hv *hv = to_kvm_hv(kvm);
1161 	u32 tsc_seq;
1162 	u64 gfn;
1163 
1164 	BUILD_BUG_ON(sizeof(tsc_seq) != sizeof(hv->tsc_ref.tsc_sequence));
1165 	BUILD_BUG_ON(offsetof(struct ms_hyperv_tsc_page, tsc_sequence) != 0);
1166 
1167 	mutex_lock(&hv->hv_lock);
1168 
1169 	if (hv->hv_tsc_page_status == HV_TSC_PAGE_BROKEN ||
1170 	    hv->hv_tsc_page_status == HV_TSC_PAGE_SET ||
1171 	    hv->hv_tsc_page_status == HV_TSC_PAGE_UNSET)
1172 		goto out_unlock;
1173 
1174 	if (!(hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE))
1175 		goto out_unlock;
1176 
1177 	gfn = hv->hv_tsc_page >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;
1178 	/*
1179 	 * Because the TSC parameters only vary when there is a
1180 	 * change in the master clock, do not bother with caching.
1181 	 */
1182 	if (unlikely(kvm_read_guest(kvm, gfn_to_gpa(gfn),
1183 				    &tsc_seq, sizeof(tsc_seq))))
1184 		goto out_err;
1185 
1186 	if (tsc_seq && tsc_page_update_unsafe(hv)) {
1187 		if (kvm_read_guest(kvm, gfn_to_gpa(gfn), &hv->tsc_ref, sizeof(hv->tsc_ref)))
1188 			goto out_err;
1189 
1190 		hv->hv_tsc_page_status = HV_TSC_PAGE_SET;
1191 		goto out_unlock;
1192 	}
1193 
1194 	/*
1195 	 * While we're computing and writing the parameters, force the
1196 	 * guest to use the time reference count MSR.
1197 	 */
1198 	hv->tsc_ref.tsc_sequence = 0;
1199 	if (kvm_write_guest(kvm, gfn_to_gpa(gfn),
1200 			    &hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence)))
1201 		goto out_err;
1202 
1203 	if (!compute_tsc_page_parameters(hv_clock, &hv->tsc_ref))
1204 		goto out_err;
1205 
1206 	/* Ensure sequence is zero before writing the rest of the struct.  */
1207 	smp_wmb();
1208 	if (kvm_write_guest(kvm, gfn_to_gpa(gfn), &hv->tsc_ref, sizeof(hv->tsc_ref)))
1209 		goto out_err;
1210 
1211 	/*
1212 	 * Now switch to the TSC page mechanism by writing the sequence.
1213 	 */
1214 	tsc_seq++;
1215 	if (tsc_seq == 0xFFFFFFFF || tsc_seq == 0)
1216 		tsc_seq = 1;
1217 
1218 	/* Write the struct entirely before the non-zero sequence.  */
1219 	smp_wmb();
1220 
1221 	hv->tsc_ref.tsc_sequence = tsc_seq;
1222 	if (kvm_write_guest(kvm, gfn_to_gpa(gfn),
1223 			    &hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence)))
1224 		goto out_err;
1225 
1226 	hv->hv_tsc_page_status = HV_TSC_PAGE_SET;
1227 	goto out_unlock;
1228 
1229 out_err:
1230 	hv->hv_tsc_page_status = HV_TSC_PAGE_BROKEN;
1231 out_unlock:
1232 	mutex_unlock(&hv->hv_lock);
1233 }
1234 
kvm_hv_request_tsc_page_update(struct kvm * kvm)1235 void kvm_hv_request_tsc_page_update(struct kvm *kvm)
1236 {
1237 	struct kvm_hv *hv = to_kvm_hv(kvm);
1238 
1239 	mutex_lock(&hv->hv_lock);
1240 
1241 	if (hv->hv_tsc_page_status == HV_TSC_PAGE_SET &&
1242 	    !tsc_page_update_unsafe(hv))
1243 		hv->hv_tsc_page_status = HV_TSC_PAGE_HOST_CHANGED;
1244 
1245 	mutex_unlock(&hv->hv_lock);
1246 }
1247 
hv_check_msr_access(struct kvm_vcpu_hv * hv_vcpu,u32 msr)1248 static bool hv_check_msr_access(struct kvm_vcpu_hv *hv_vcpu, u32 msr)
1249 {
1250 	if (!hv_vcpu->enforce_cpuid)
1251 		return true;
1252 
1253 	switch (msr) {
1254 	case HV_X64_MSR_GUEST_OS_ID:
1255 	case HV_X64_MSR_HYPERCALL:
1256 		return hv_vcpu->cpuid_cache.features_eax &
1257 			HV_MSR_HYPERCALL_AVAILABLE;
1258 	case HV_X64_MSR_VP_RUNTIME:
1259 		return hv_vcpu->cpuid_cache.features_eax &
1260 			HV_MSR_VP_RUNTIME_AVAILABLE;
1261 	case HV_X64_MSR_TIME_REF_COUNT:
1262 		return hv_vcpu->cpuid_cache.features_eax &
1263 			HV_MSR_TIME_REF_COUNT_AVAILABLE;
1264 	case HV_X64_MSR_VP_INDEX:
1265 		return hv_vcpu->cpuid_cache.features_eax &
1266 			HV_MSR_VP_INDEX_AVAILABLE;
1267 	case HV_X64_MSR_RESET:
1268 		return hv_vcpu->cpuid_cache.features_eax &
1269 			HV_MSR_RESET_AVAILABLE;
1270 	case HV_X64_MSR_REFERENCE_TSC:
1271 		return hv_vcpu->cpuid_cache.features_eax &
1272 			HV_MSR_REFERENCE_TSC_AVAILABLE;
1273 	case HV_X64_MSR_SCONTROL:
1274 	case HV_X64_MSR_SVERSION:
1275 	case HV_X64_MSR_SIEFP:
1276 	case HV_X64_MSR_SIMP:
1277 	case HV_X64_MSR_EOM:
1278 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1279 		return hv_vcpu->cpuid_cache.features_eax &
1280 			HV_MSR_SYNIC_AVAILABLE;
1281 	case HV_X64_MSR_STIMER0_CONFIG:
1282 	case HV_X64_MSR_STIMER1_CONFIG:
1283 	case HV_X64_MSR_STIMER2_CONFIG:
1284 	case HV_X64_MSR_STIMER3_CONFIG:
1285 	case HV_X64_MSR_STIMER0_COUNT:
1286 	case HV_X64_MSR_STIMER1_COUNT:
1287 	case HV_X64_MSR_STIMER2_COUNT:
1288 	case HV_X64_MSR_STIMER3_COUNT:
1289 		return hv_vcpu->cpuid_cache.features_eax &
1290 			HV_MSR_SYNTIMER_AVAILABLE;
1291 	case HV_X64_MSR_EOI:
1292 	case HV_X64_MSR_ICR:
1293 	case HV_X64_MSR_TPR:
1294 	case HV_X64_MSR_VP_ASSIST_PAGE:
1295 		return hv_vcpu->cpuid_cache.features_eax &
1296 			HV_MSR_APIC_ACCESS_AVAILABLE;
1297 	case HV_X64_MSR_TSC_FREQUENCY:
1298 	case HV_X64_MSR_APIC_FREQUENCY:
1299 		return hv_vcpu->cpuid_cache.features_eax &
1300 			HV_ACCESS_FREQUENCY_MSRS;
1301 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1302 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
1303 	case HV_X64_MSR_TSC_EMULATION_STATUS:
1304 		return hv_vcpu->cpuid_cache.features_eax &
1305 			HV_ACCESS_REENLIGHTENMENT;
1306 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
1307 		return hv_vcpu->cpuid_cache.features_eax &
1308 			HV_ACCESS_TSC_INVARIANT;
1309 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1310 	case HV_X64_MSR_CRASH_CTL:
1311 		return hv_vcpu->cpuid_cache.features_edx &
1312 			HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE;
1313 	case HV_X64_MSR_SYNDBG_OPTIONS:
1314 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
1315 		return hv_vcpu->cpuid_cache.features_edx &
1316 			HV_FEATURE_DEBUG_MSRS_AVAILABLE;
1317 	default:
1318 		break;
1319 	}
1320 
1321 	return false;
1322 }
1323 
1324 #define KVM_HV_WIN2016_GUEST_ID 0x1040a00003839
1325 #define KVM_HV_WIN2016_GUEST_ID_MASK (~GENMASK_ULL(23, 16)) /* mask out the service version */
1326 
1327 /*
1328  * Hyper-V enabled Windows Server 2016 SMP VMs fail to boot in !XSAVES && XSAVEC
1329  * configuration.
1330  * Such configuration can result from, for example, AMD Erratum 1386 workaround.
1331  *
1332  * Print a notice so users aren't left wondering what's suddenly gone wrong.
1333  */
__kvm_hv_xsaves_xsavec_maybe_warn(struct kvm_vcpu * vcpu)1334 static void __kvm_hv_xsaves_xsavec_maybe_warn(struct kvm_vcpu *vcpu)
1335 {
1336 	struct kvm *kvm = vcpu->kvm;
1337 	struct kvm_hv *hv = to_kvm_hv(kvm);
1338 
1339 	/* Check again under the hv_lock.  */
1340 	if (hv->xsaves_xsavec_checked)
1341 		return;
1342 
1343 	if ((hv->hv_guest_os_id & KVM_HV_WIN2016_GUEST_ID_MASK) !=
1344 	    KVM_HV_WIN2016_GUEST_ID)
1345 		return;
1346 
1347 	hv->xsaves_xsavec_checked = true;
1348 
1349 	/* UP configurations aren't affected */
1350 	if (atomic_read(&kvm->online_vcpus) < 2)
1351 		return;
1352 
1353 	if (guest_cpuid_has(vcpu, X86_FEATURE_XSAVES) ||
1354 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVEC))
1355 		return;
1356 
1357 	pr_notice_ratelimited("Booting SMP Windows KVM VM with !XSAVES && XSAVEC. "
1358 			      "If it fails to boot try disabling XSAVEC in the VM config.\n");
1359 }
1360 
kvm_hv_xsaves_xsavec_maybe_warn(struct kvm_vcpu * vcpu)1361 void kvm_hv_xsaves_xsavec_maybe_warn(struct kvm_vcpu *vcpu)
1362 {
1363 	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
1364 
1365 	if (!vcpu->arch.hyperv_enabled ||
1366 	    hv->xsaves_xsavec_checked)
1367 		return;
1368 
1369 	mutex_lock(&hv->hv_lock);
1370 	__kvm_hv_xsaves_xsavec_maybe_warn(vcpu);
1371 	mutex_unlock(&hv->hv_lock);
1372 }
1373 
kvm_hv_set_msr_pw(struct kvm_vcpu * vcpu,u32 msr,u64 data,bool host)1374 static int kvm_hv_set_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data,
1375 			     bool host)
1376 {
1377 	struct kvm *kvm = vcpu->kvm;
1378 	struct kvm_hv *hv = to_kvm_hv(kvm);
1379 
1380 	if (unlikely(!host && !hv_check_msr_access(to_hv_vcpu(vcpu), msr)))
1381 		return 1;
1382 
1383 	switch (msr) {
1384 	case HV_X64_MSR_GUEST_OS_ID:
1385 		hv->hv_guest_os_id = data;
1386 		/* setting guest os id to zero disables hypercall page */
1387 		if (!hv->hv_guest_os_id)
1388 			hv->hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1389 		break;
1390 	case HV_X64_MSR_HYPERCALL: {
1391 		u8 instructions[9];
1392 		int i = 0;
1393 		u64 addr;
1394 
1395 		/* if guest os id is not set hypercall should remain disabled */
1396 		if (!hv->hv_guest_os_id)
1397 			break;
1398 		if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1399 			hv->hv_hypercall = data;
1400 			break;
1401 		}
1402 
1403 		/*
1404 		 * If Xen and Hyper-V hypercalls are both enabled, disambiguate
1405 		 * the same way Xen itself does, by setting the bit 31 of EAX
1406 		 * which is RsvdZ in the 32-bit Hyper-V hypercall ABI and just
1407 		 * going to be clobbered on 64-bit.
1408 		 */
1409 		if (kvm_xen_hypercall_enabled(kvm)) {
1410 			/* orl $0x80000000, %eax */
1411 			instructions[i++] = 0x0d;
1412 			instructions[i++] = 0x00;
1413 			instructions[i++] = 0x00;
1414 			instructions[i++] = 0x00;
1415 			instructions[i++] = 0x80;
1416 		}
1417 
1418 		/* vmcall/vmmcall */
1419 		kvm_x86_call(patch_hypercall)(vcpu, instructions + i);
1420 		i += 3;
1421 
1422 		/* ret */
1423 		((unsigned char *)instructions)[i++] = 0xc3;
1424 
1425 		addr = data & HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_MASK;
1426 		if (kvm_vcpu_write_guest(vcpu, addr, instructions, i))
1427 			return 1;
1428 		hv->hv_hypercall = data;
1429 		break;
1430 	}
1431 	case HV_X64_MSR_REFERENCE_TSC:
1432 		hv->hv_tsc_page = data;
1433 		if (hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE) {
1434 			if (!host)
1435 				hv->hv_tsc_page_status = HV_TSC_PAGE_GUEST_CHANGED;
1436 			else
1437 				hv->hv_tsc_page_status = HV_TSC_PAGE_HOST_CHANGED;
1438 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1439 		} else {
1440 			hv->hv_tsc_page_status = HV_TSC_PAGE_UNSET;
1441 		}
1442 		break;
1443 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1444 		return kvm_hv_msr_set_crash_data(kvm,
1445 						 msr - HV_X64_MSR_CRASH_P0,
1446 						 data);
1447 	case HV_X64_MSR_CRASH_CTL:
1448 		if (host)
1449 			return kvm_hv_msr_set_crash_ctl(kvm, data);
1450 
1451 		if (data & HV_CRASH_CTL_CRASH_NOTIFY) {
1452 			vcpu_debug(vcpu, "hv crash (0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n",
1453 				   hv->hv_crash_param[0],
1454 				   hv->hv_crash_param[1],
1455 				   hv->hv_crash_param[2],
1456 				   hv->hv_crash_param[3],
1457 				   hv->hv_crash_param[4]);
1458 
1459 			/* Send notification about crash to user space */
1460 			kvm_make_request(KVM_REQ_HV_CRASH, vcpu);
1461 		}
1462 		break;
1463 	case HV_X64_MSR_RESET:
1464 		if (data == 1) {
1465 			vcpu_debug(vcpu, "hyper-v reset requested\n");
1466 			kvm_make_request(KVM_REQ_HV_RESET, vcpu);
1467 		}
1468 		break;
1469 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1470 		hv->hv_reenlightenment_control = data;
1471 		break;
1472 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
1473 		hv->hv_tsc_emulation_control = data;
1474 		break;
1475 	case HV_X64_MSR_TSC_EMULATION_STATUS:
1476 		if (data && !host)
1477 			return 1;
1478 
1479 		hv->hv_tsc_emulation_status = data;
1480 		break;
1481 	case HV_X64_MSR_TIME_REF_COUNT:
1482 		/* read-only, but still ignore it if host-initiated */
1483 		if (!host)
1484 			return 1;
1485 		break;
1486 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
1487 		/* Only bit 0 is supported */
1488 		if (data & ~HV_EXPOSE_INVARIANT_TSC)
1489 			return 1;
1490 
1491 		/* The feature can't be disabled from the guest */
1492 		if (!host && hv->hv_invtsc_control && !data)
1493 			return 1;
1494 
1495 		hv->hv_invtsc_control = data;
1496 		break;
1497 	case HV_X64_MSR_SYNDBG_OPTIONS:
1498 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
1499 		return syndbg_set_msr(vcpu, msr, data, host);
1500 	default:
1501 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
1502 		return 1;
1503 	}
1504 	return 0;
1505 }
1506 
1507 /* Calculate cpu time spent by current task in 100ns units */
current_task_runtime_100ns(void)1508 static u64 current_task_runtime_100ns(void)
1509 {
1510 	u64 utime, stime;
1511 
1512 	task_cputime_adjusted(current, &utime, &stime);
1513 
1514 	return div_u64(utime + stime, 100);
1515 }
1516 
kvm_hv_set_msr(struct kvm_vcpu * vcpu,u32 msr,u64 data,bool host)1517 static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1518 {
1519 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1520 
1521 	if (unlikely(!host && !hv_check_msr_access(hv_vcpu, msr)))
1522 		return 1;
1523 
1524 	switch (msr) {
1525 	case HV_X64_MSR_VP_INDEX: {
1526 		struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
1527 		u32 new_vp_index = (u32)data;
1528 
1529 		if (!host || new_vp_index >= KVM_MAX_VCPUS)
1530 			return 1;
1531 
1532 		if (new_vp_index == hv_vcpu->vp_index)
1533 			return 0;
1534 
1535 		/*
1536 		 * The VP index is initialized to vcpu_index by
1537 		 * kvm_hv_vcpu_postcreate so they initially match.  Now the
1538 		 * VP index is changing, adjust num_mismatched_vp_indexes if
1539 		 * it now matches or no longer matches vcpu_idx.
1540 		 */
1541 		if (hv_vcpu->vp_index == vcpu->vcpu_idx)
1542 			atomic_inc(&hv->num_mismatched_vp_indexes);
1543 		else if (new_vp_index == vcpu->vcpu_idx)
1544 			atomic_dec(&hv->num_mismatched_vp_indexes);
1545 
1546 		hv_vcpu->vp_index = new_vp_index;
1547 		break;
1548 	}
1549 	case HV_X64_MSR_VP_ASSIST_PAGE: {
1550 		u64 gfn;
1551 		unsigned long addr;
1552 
1553 		if (!(data & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE)) {
1554 			hv_vcpu->hv_vapic = data;
1555 			if (kvm_lapic_set_pv_eoi(vcpu, 0, 0))
1556 				return 1;
1557 			break;
1558 		}
1559 		gfn = data >> HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_SHIFT;
1560 		addr = kvm_vcpu_gfn_to_hva(vcpu, gfn);
1561 		if (kvm_is_error_hva(addr))
1562 			return 1;
1563 
1564 		/*
1565 		 * Clear apic_assist portion of struct hv_vp_assist_page
1566 		 * only, there can be valuable data in the rest which needs
1567 		 * to be preserved e.g. on migration.
1568 		 */
1569 		if (__put_user(0, (u32 __user *)addr))
1570 			return 1;
1571 		hv_vcpu->hv_vapic = data;
1572 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
1573 		if (kvm_lapic_set_pv_eoi(vcpu,
1574 					    gfn_to_gpa(gfn) | KVM_MSR_ENABLED,
1575 					    sizeof(struct hv_vp_assist_page)))
1576 			return 1;
1577 		break;
1578 	}
1579 	case HV_X64_MSR_EOI:
1580 		return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1581 	case HV_X64_MSR_ICR:
1582 		return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1583 	case HV_X64_MSR_TPR:
1584 		return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1585 	case HV_X64_MSR_VP_RUNTIME:
1586 		if (!host)
1587 			return 1;
1588 		hv_vcpu->runtime_offset = data - current_task_runtime_100ns();
1589 		break;
1590 	case HV_X64_MSR_SCONTROL:
1591 	case HV_X64_MSR_SVERSION:
1592 	case HV_X64_MSR_SIEFP:
1593 	case HV_X64_MSR_SIMP:
1594 	case HV_X64_MSR_EOM:
1595 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1596 		return synic_set_msr(to_hv_synic(vcpu), msr, data, host);
1597 	case HV_X64_MSR_STIMER0_CONFIG:
1598 	case HV_X64_MSR_STIMER1_CONFIG:
1599 	case HV_X64_MSR_STIMER2_CONFIG:
1600 	case HV_X64_MSR_STIMER3_CONFIG: {
1601 		int timer_index = (msr - HV_X64_MSR_STIMER0_CONFIG)/2;
1602 
1603 		return stimer_set_config(to_hv_stimer(vcpu, timer_index),
1604 					 data, host);
1605 	}
1606 	case HV_X64_MSR_STIMER0_COUNT:
1607 	case HV_X64_MSR_STIMER1_COUNT:
1608 	case HV_X64_MSR_STIMER2_COUNT:
1609 	case HV_X64_MSR_STIMER3_COUNT: {
1610 		int timer_index = (msr - HV_X64_MSR_STIMER0_COUNT)/2;
1611 
1612 		return stimer_set_count(to_hv_stimer(vcpu, timer_index),
1613 					data, host);
1614 	}
1615 	case HV_X64_MSR_TSC_FREQUENCY:
1616 	case HV_X64_MSR_APIC_FREQUENCY:
1617 		/* read-only, but still ignore it if host-initiated */
1618 		if (!host)
1619 			return 1;
1620 		break;
1621 	default:
1622 		kvm_pr_unimpl_wrmsr(vcpu, msr, data);
1623 		return 1;
1624 	}
1625 
1626 	return 0;
1627 }
1628 
kvm_hv_get_msr_pw(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)1629 static int kvm_hv_get_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
1630 			     bool host)
1631 {
1632 	u64 data = 0;
1633 	struct kvm *kvm = vcpu->kvm;
1634 	struct kvm_hv *hv = to_kvm_hv(kvm);
1635 
1636 	if (unlikely(!host && !hv_check_msr_access(to_hv_vcpu(vcpu), msr)))
1637 		return 1;
1638 
1639 	switch (msr) {
1640 	case HV_X64_MSR_GUEST_OS_ID:
1641 		data = hv->hv_guest_os_id;
1642 		break;
1643 	case HV_X64_MSR_HYPERCALL:
1644 		data = hv->hv_hypercall;
1645 		break;
1646 	case HV_X64_MSR_TIME_REF_COUNT:
1647 		data = get_time_ref_counter(kvm);
1648 		break;
1649 	case HV_X64_MSR_REFERENCE_TSC:
1650 		data = hv->hv_tsc_page;
1651 		break;
1652 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1653 		return kvm_hv_msr_get_crash_data(kvm,
1654 						 msr - HV_X64_MSR_CRASH_P0,
1655 						 pdata);
1656 	case HV_X64_MSR_CRASH_CTL:
1657 		return kvm_hv_msr_get_crash_ctl(kvm, pdata);
1658 	case HV_X64_MSR_RESET:
1659 		data = 0;
1660 		break;
1661 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1662 		data = hv->hv_reenlightenment_control;
1663 		break;
1664 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
1665 		data = hv->hv_tsc_emulation_control;
1666 		break;
1667 	case HV_X64_MSR_TSC_EMULATION_STATUS:
1668 		data = hv->hv_tsc_emulation_status;
1669 		break;
1670 	case HV_X64_MSR_TSC_INVARIANT_CONTROL:
1671 		data = hv->hv_invtsc_control;
1672 		break;
1673 	case HV_X64_MSR_SYNDBG_OPTIONS:
1674 	case HV_X64_MSR_SYNDBG_CONTROL ... HV_X64_MSR_SYNDBG_PENDING_BUFFER:
1675 		return syndbg_get_msr(vcpu, msr, pdata, host);
1676 	default:
1677 		kvm_pr_unimpl_rdmsr(vcpu, msr);
1678 		return 1;
1679 	}
1680 
1681 	*pdata = data;
1682 	return 0;
1683 }
1684 
kvm_hv_get_msr(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)1685 static int kvm_hv_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
1686 			  bool host)
1687 {
1688 	u64 data = 0;
1689 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1690 
1691 	if (unlikely(!host && !hv_check_msr_access(hv_vcpu, msr)))
1692 		return 1;
1693 
1694 	switch (msr) {
1695 	case HV_X64_MSR_VP_INDEX:
1696 		data = hv_vcpu->vp_index;
1697 		break;
1698 	case HV_X64_MSR_EOI:
1699 		return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1700 	case HV_X64_MSR_ICR:
1701 		return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1702 	case HV_X64_MSR_TPR:
1703 		return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1704 	case HV_X64_MSR_VP_ASSIST_PAGE:
1705 		data = hv_vcpu->hv_vapic;
1706 		break;
1707 	case HV_X64_MSR_VP_RUNTIME:
1708 		data = current_task_runtime_100ns() + hv_vcpu->runtime_offset;
1709 		break;
1710 	case HV_X64_MSR_SCONTROL:
1711 	case HV_X64_MSR_SVERSION:
1712 	case HV_X64_MSR_SIEFP:
1713 	case HV_X64_MSR_SIMP:
1714 	case HV_X64_MSR_EOM:
1715 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1716 		return synic_get_msr(to_hv_synic(vcpu), msr, pdata, host);
1717 	case HV_X64_MSR_STIMER0_CONFIG:
1718 	case HV_X64_MSR_STIMER1_CONFIG:
1719 	case HV_X64_MSR_STIMER2_CONFIG:
1720 	case HV_X64_MSR_STIMER3_CONFIG: {
1721 		int timer_index = (msr - HV_X64_MSR_STIMER0_CONFIG)/2;
1722 
1723 		return stimer_get_config(to_hv_stimer(vcpu, timer_index),
1724 					 pdata);
1725 	}
1726 	case HV_X64_MSR_STIMER0_COUNT:
1727 	case HV_X64_MSR_STIMER1_COUNT:
1728 	case HV_X64_MSR_STIMER2_COUNT:
1729 	case HV_X64_MSR_STIMER3_COUNT: {
1730 		int timer_index = (msr - HV_X64_MSR_STIMER0_COUNT)/2;
1731 
1732 		return stimer_get_count(to_hv_stimer(vcpu, timer_index),
1733 					pdata);
1734 	}
1735 	case HV_X64_MSR_TSC_FREQUENCY:
1736 		data = (u64)vcpu->arch.virtual_tsc_khz * 1000;
1737 		break;
1738 	case HV_X64_MSR_APIC_FREQUENCY:
1739 		data = div64_u64(1000000000ULL,
1740 				 vcpu->kvm->arch.apic_bus_cycle_ns);
1741 		break;
1742 	default:
1743 		kvm_pr_unimpl_rdmsr(vcpu, msr);
1744 		return 1;
1745 	}
1746 	*pdata = data;
1747 	return 0;
1748 }
1749 
kvm_hv_set_msr_common(struct kvm_vcpu * vcpu,u32 msr,u64 data,bool host)1750 int kvm_hv_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1751 {
1752 	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
1753 
1754 	if (!host && !vcpu->arch.hyperv_enabled)
1755 		return 1;
1756 
1757 	if (kvm_hv_vcpu_init(vcpu))
1758 		return 1;
1759 
1760 	if (kvm_hv_msr_partition_wide(msr)) {
1761 		int r;
1762 
1763 		mutex_lock(&hv->hv_lock);
1764 		r = kvm_hv_set_msr_pw(vcpu, msr, data, host);
1765 		mutex_unlock(&hv->hv_lock);
1766 		return r;
1767 	} else
1768 		return kvm_hv_set_msr(vcpu, msr, data, host);
1769 }
1770 
kvm_hv_get_msr_common(struct kvm_vcpu * vcpu,u32 msr,u64 * pdata,bool host)1771 int kvm_hv_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
1772 {
1773 	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
1774 
1775 	if (!host && !vcpu->arch.hyperv_enabled)
1776 		return 1;
1777 
1778 	if (kvm_hv_vcpu_init(vcpu))
1779 		return 1;
1780 
1781 	if (kvm_hv_msr_partition_wide(msr)) {
1782 		int r;
1783 
1784 		mutex_lock(&hv->hv_lock);
1785 		r = kvm_hv_get_msr_pw(vcpu, msr, pdata, host);
1786 		mutex_unlock(&hv->hv_lock);
1787 		return r;
1788 	} else
1789 		return kvm_hv_get_msr(vcpu, msr, pdata, host);
1790 }
1791 
sparse_set_to_vcpu_mask(struct kvm * kvm,u64 * sparse_banks,u64 valid_bank_mask,unsigned long * vcpu_mask)1792 static void sparse_set_to_vcpu_mask(struct kvm *kvm, u64 *sparse_banks,
1793 				    u64 valid_bank_mask, unsigned long *vcpu_mask)
1794 {
1795 	struct kvm_hv *hv = to_kvm_hv(kvm);
1796 	bool has_mismatch = atomic_read(&hv->num_mismatched_vp_indexes);
1797 	u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
1798 	struct kvm_vcpu *vcpu;
1799 	int bank, sbank = 0;
1800 	unsigned long i;
1801 	u64 *bitmap;
1802 
1803 	BUILD_BUG_ON(sizeof(vp_bitmap) >
1804 		     sizeof(*vcpu_mask) * BITS_TO_LONGS(KVM_MAX_VCPUS));
1805 
1806 	/*
1807 	 * If vp_index == vcpu_idx for all vCPUs, fill vcpu_mask directly, else
1808 	 * fill a temporary buffer and manually test each vCPU's VP index.
1809 	 */
1810 	if (likely(!has_mismatch))
1811 		bitmap = (u64 *)vcpu_mask;
1812 	else
1813 		bitmap = vp_bitmap;
1814 
1815 	/*
1816 	 * Each set of 64 VPs is packed into sparse_banks, with valid_bank_mask
1817 	 * having a '1' for each bank that exists in sparse_banks.  Sets must
1818 	 * be in ascending order, i.e. bank0..bankN.
1819 	 */
1820 	memset(bitmap, 0, sizeof(vp_bitmap));
1821 	for_each_set_bit(bank, (unsigned long *)&valid_bank_mask,
1822 			 KVM_HV_MAX_SPARSE_VCPU_SET_BITS)
1823 		bitmap[bank] = sparse_banks[sbank++];
1824 
1825 	if (likely(!has_mismatch))
1826 		return;
1827 
1828 	bitmap_zero(vcpu_mask, KVM_MAX_VCPUS);
1829 	kvm_for_each_vcpu(i, vcpu, kvm) {
1830 		if (test_bit(kvm_hv_get_vpindex(vcpu), (unsigned long *)vp_bitmap))
1831 			__set_bit(i, vcpu_mask);
1832 	}
1833 }
1834 
hv_is_vp_in_sparse_set(u32 vp_id,u64 valid_bank_mask,u64 sparse_banks[])1835 static bool hv_is_vp_in_sparse_set(u32 vp_id, u64 valid_bank_mask, u64 sparse_banks[])
1836 {
1837 	int valid_bit_nr = vp_id / HV_VCPUS_PER_SPARSE_BANK;
1838 	unsigned long sbank;
1839 
1840 	if (!test_bit(valid_bit_nr, (unsigned long *)&valid_bank_mask))
1841 		return false;
1842 
1843 	/*
1844 	 * The index into the sparse bank is the number of preceding bits in
1845 	 * the valid mask.  Optimize for VMs with <64 vCPUs by skipping the
1846 	 * fancy math if there can't possibly be preceding bits.
1847 	 */
1848 	if (valid_bit_nr)
1849 		sbank = hweight64(valid_bank_mask & GENMASK_ULL(valid_bit_nr - 1, 0));
1850 	else
1851 		sbank = 0;
1852 
1853 	return test_bit(vp_id % HV_VCPUS_PER_SPARSE_BANK,
1854 			(unsigned long *)&sparse_banks[sbank]);
1855 }
1856 
1857 struct kvm_hv_hcall {
1858 	/* Hypercall input data */
1859 	u64 param;
1860 	u64 ingpa;
1861 	u64 outgpa;
1862 	u16 code;
1863 	u16 var_cnt;
1864 	u16 rep_cnt;
1865 	u16 rep_idx;
1866 	bool fast;
1867 	bool rep;
1868 	sse128_t xmm[HV_HYPERCALL_MAX_XMM_REGISTERS];
1869 
1870 	/*
1871 	 * Current read offset when KVM reads hypercall input data gradually,
1872 	 * either offset in bytes from 'ingpa' for regular hypercalls or the
1873 	 * number of already consumed 'XMM halves' for 'fast' hypercalls.
1874 	 */
1875 	union {
1876 		gpa_t data_offset;
1877 		int consumed_xmm_halves;
1878 	};
1879 };
1880 
1881 
kvm_hv_get_hc_data(struct kvm * kvm,struct kvm_hv_hcall * hc,u16 orig_cnt,u16 cnt_cap,u64 * data)1882 static int kvm_hv_get_hc_data(struct kvm *kvm, struct kvm_hv_hcall *hc,
1883 			      u16 orig_cnt, u16 cnt_cap, u64 *data)
1884 {
1885 	/*
1886 	 * Preserve the original count when ignoring entries via a "cap", KVM
1887 	 * still needs to validate the guest input (though the non-XMM path
1888 	 * punts on the checks).
1889 	 */
1890 	u16 cnt = min(orig_cnt, cnt_cap);
1891 	int i, j;
1892 
1893 	if (hc->fast) {
1894 		/*
1895 		 * Each XMM holds two sparse banks, but do not count halves that
1896 		 * have already been consumed for hypercall parameters.
1897 		 */
1898 		if (orig_cnt > 2 * HV_HYPERCALL_MAX_XMM_REGISTERS - hc->consumed_xmm_halves)
1899 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
1900 
1901 		for (i = 0; i < cnt; i++) {
1902 			j = i + hc->consumed_xmm_halves;
1903 			if (j % 2)
1904 				data[i] = sse128_hi(hc->xmm[j / 2]);
1905 			else
1906 				data[i] = sse128_lo(hc->xmm[j / 2]);
1907 		}
1908 		return 0;
1909 	}
1910 
1911 	return kvm_read_guest(kvm, hc->ingpa + hc->data_offset, data,
1912 			      cnt * sizeof(*data));
1913 }
1914 
kvm_get_sparse_vp_set(struct kvm * kvm,struct kvm_hv_hcall * hc,u64 * sparse_banks)1915 static u64 kvm_get_sparse_vp_set(struct kvm *kvm, struct kvm_hv_hcall *hc,
1916 				 u64 *sparse_banks)
1917 {
1918 	if (hc->var_cnt > HV_MAX_SPARSE_VCPU_BANKS)
1919 		return -EINVAL;
1920 
1921 	/* Cap var_cnt to ignore banks that cannot contain a legal VP index. */
1922 	return kvm_hv_get_hc_data(kvm, hc, hc->var_cnt, KVM_HV_MAX_SPARSE_VCPU_SET_BITS,
1923 				  sparse_banks);
1924 }
1925 
kvm_hv_get_tlb_flush_entries(struct kvm * kvm,struct kvm_hv_hcall * hc,u64 entries[])1926 static int kvm_hv_get_tlb_flush_entries(struct kvm *kvm, struct kvm_hv_hcall *hc, u64 entries[])
1927 {
1928 	return kvm_hv_get_hc_data(kvm, hc, hc->rep_cnt, hc->rep_cnt, entries);
1929 }
1930 
hv_tlb_flush_enqueue(struct kvm_vcpu * vcpu,struct kvm_vcpu_hv_tlb_flush_fifo * tlb_flush_fifo,u64 * entries,int count)1931 static void hv_tlb_flush_enqueue(struct kvm_vcpu *vcpu,
1932 				 struct kvm_vcpu_hv_tlb_flush_fifo *tlb_flush_fifo,
1933 				 u64 *entries, int count)
1934 {
1935 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1936 	u64 flush_all_entry = KVM_HV_TLB_FLUSHALL_ENTRY;
1937 
1938 	if (!hv_vcpu)
1939 		return;
1940 
1941 	spin_lock(&tlb_flush_fifo->write_lock);
1942 
1943 	/*
1944 	 * All entries should fit on the fifo leaving one free for 'flush all'
1945 	 * entry in case another request comes in. In case there's not enough
1946 	 * space, just put 'flush all' entry there.
1947 	 */
1948 	if (count && entries && count < kfifo_avail(&tlb_flush_fifo->entries)) {
1949 		WARN_ON(kfifo_in(&tlb_flush_fifo->entries, entries, count) != count);
1950 		goto out_unlock;
1951 	}
1952 
1953 	/*
1954 	 * Note: full fifo always contains 'flush all' entry, no need to check the
1955 	 * return value.
1956 	 */
1957 	kfifo_in(&tlb_flush_fifo->entries, &flush_all_entry, 1);
1958 
1959 out_unlock:
1960 	spin_unlock(&tlb_flush_fifo->write_lock);
1961 }
1962 
kvm_hv_vcpu_flush_tlb(struct kvm_vcpu * vcpu)1963 int kvm_hv_vcpu_flush_tlb(struct kvm_vcpu *vcpu)
1964 {
1965 	struct kvm_vcpu_hv_tlb_flush_fifo *tlb_flush_fifo;
1966 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
1967 	u64 entries[KVM_HV_TLB_FLUSH_FIFO_SIZE];
1968 	int i, j, count;
1969 	gva_t gva;
1970 
1971 	if (!tdp_enabled || !hv_vcpu)
1972 		return -EINVAL;
1973 
1974 	tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(vcpu, is_guest_mode(vcpu));
1975 
1976 	count = kfifo_out(&tlb_flush_fifo->entries, entries, KVM_HV_TLB_FLUSH_FIFO_SIZE);
1977 
1978 	for (i = 0; i < count; i++) {
1979 		if (entries[i] == KVM_HV_TLB_FLUSHALL_ENTRY)
1980 			goto out_flush_all;
1981 
1982 		if (is_noncanonical_invlpg_address(entries[i], vcpu))
1983 			continue;
1984 
1985 		/*
1986 		 * Lower 12 bits of 'address' encode the number of additional
1987 		 * pages to flush.
1988 		 */
1989 		gva = entries[i] & PAGE_MASK;
1990 		for (j = 0; j < (entries[i] & ~PAGE_MASK) + 1; j++)
1991 			kvm_x86_call(flush_tlb_gva)(vcpu, gva + j * PAGE_SIZE);
1992 
1993 		++vcpu->stat.tlb_flush;
1994 	}
1995 	return 0;
1996 
1997 out_flush_all:
1998 	kfifo_reset_out(&tlb_flush_fifo->entries);
1999 
2000 	/* Fall back to full flush. */
2001 	return -ENOSPC;
2002 }
2003 
kvm_hv_flush_tlb(struct kvm_vcpu * vcpu,struct kvm_hv_hcall * hc)2004 static u64 kvm_hv_flush_tlb(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc)
2005 {
2006 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
2007 	unsigned long *vcpu_mask = hv_vcpu->vcpu_mask;
2008 	u64 *sparse_banks = hv_vcpu->sparse_banks;
2009 	struct kvm *kvm = vcpu->kvm;
2010 	struct hv_tlb_flush_ex flush_ex;
2011 	struct hv_tlb_flush flush;
2012 	struct kvm_vcpu_hv_tlb_flush_fifo *tlb_flush_fifo;
2013 	/*
2014 	 * Normally, there can be no more than 'KVM_HV_TLB_FLUSH_FIFO_SIZE'
2015 	 * entries on the TLB flush fifo. The last entry, however, needs to be
2016 	 * always left free for 'flush all' entry which gets placed when
2017 	 * there is not enough space to put all the requested entries.
2018 	 */
2019 	u64 __tlb_flush_entries[KVM_HV_TLB_FLUSH_FIFO_SIZE - 1];
2020 	u64 *tlb_flush_entries;
2021 	u64 valid_bank_mask;
2022 	struct kvm_vcpu *v;
2023 	unsigned long i;
2024 	bool all_cpus;
2025 
2026 	/*
2027 	 * The Hyper-V TLFS doesn't allow more than HV_MAX_SPARSE_VCPU_BANKS
2028 	 * sparse banks. Fail the build if KVM's max allowed number of
2029 	 * vCPUs (>4096) exceeds this limit.
2030 	 */
2031 	BUILD_BUG_ON(KVM_HV_MAX_SPARSE_VCPU_SET_BITS > HV_MAX_SPARSE_VCPU_BANKS);
2032 
2033 	/*
2034 	 * 'Slow' hypercall's first parameter is the address in guest's memory
2035 	 * where hypercall parameters are placed. This is either a GPA or a
2036 	 * nested GPA when KVM is handling the call from L2 ('direct' TLB
2037 	 * flush).  Translate the address here so the memory can be uniformly
2038 	 * read with kvm_read_guest().
2039 	 */
2040 	if (!hc->fast && is_guest_mode(vcpu)) {
2041 		hc->ingpa = translate_nested_gpa(vcpu, hc->ingpa, 0, NULL);
2042 		if (unlikely(hc->ingpa == INVALID_GPA))
2043 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
2044 	}
2045 
2046 	if (hc->code == HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST ||
2047 	    hc->code == HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE) {
2048 		if (hc->fast) {
2049 			flush.address_space = hc->ingpa;
2050 			flush.flags = hc->outgpa;
2051 			flush.processor_mask = sse128_lo(hc->xmm[0]);
2052 			hc->consumed_xmm_halves = 1;
2053 		} else {
2054 			if (unlikely(kvm_read_guest(kvm, hc->ingpa,
2055 						    &flush, sizeof(flush))))
2056 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
2057 			hc->data_offset = sizeof(flush);
2058 		}
2059 
2060 		trace_kvm_hv_flush_tlb(flush.processor_mask,
2061 				       flush.address_space, flush.flags,
2062 				       is_guest_mode(vcpu));
2063 
2064 		valid_bank_mask = BIT_ULL(0);
2065 		sparse_banks[0] = flush.processor_mask;
2066 
2067 		/*
2068 		 * Work around possible WS2012 bug: it sends hypercalls
2069 		 * with processor_mask = 0x0 and HV_FLUSH_ALL_PROCESSORS clear,
2070 		 * while also expecting us to flush something and crashing if
2071 		 * we don't. Let's treat processor_mask == 0 same as
2072 		 * HV_FLUSH_ALL_PROCESSORS.
2073 		 */
2074 		all_cpus = (flush.flags & HV_FLUSH_ALL_PROCESSORS) ||
2075 			flush.processor_mask == 0;
2076 	} else {
2077 		if (hc->fast) {
2078 			flush_ex.address_space = hc->ingpa;
2079 			flush_ex.flags = hc->outgpa;
2080 			memcpy(&flush_ex.hv_vp_set,
2081 			       &hc->xmm[0], sizeof(hc->xmm[0]));
2082 			hc->consumed_xmm_halves = 2;
2083 		} else {
2084 			if (unlikely(kvm_read_guest(kvm, hc->ingpa, &flush_ex,
2085 						    sizeof(flush_ex))))
2086 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
2087 			hc->data_offset = sizeof(flush_ex);
2088 		}
2089 
2090 		trace_kvm_hv_flush_tlb_ex(flush_ex.hv_vp_set.valid_bank_mask,
2091 					  flush_ex.hv_vp_set.format,
2092 					  flush_ex.address_space,
2093 					  flush_ex.flags, is_guest_mode(vcpu));
2094 
2095 		valid_bank_mask = flush_ex.hv_vp_set.valid_bank_mask;
2096 		all_cpus = flush_ex.hv_vp_set.format !=
2097 			HV_GENERIC_SET_SPARSE_4K;
2098 
2099 		if (hc->var_cnt != hweight64(valid_bank_mask))
2100 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
2101 
2102 		if (!all_cpus) {
2103 			if (!hc->var_cnt)
2104 				goto ret_success;
2105 
2106 			if (kvm_get_sparse_vp_set(kvm, hc, sparse_banks))
2107 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
2108 		}
2109 
2110 		/*
2111 		 * Hyper-V TLFS doesn't explicitly forbid non-empty sparse vCPU
2112 		 * banks (and, thus, non-zero 'var_cnt') for the 'all vCPUs'
2113 		 * case (HV_GENERIC_SET_ALL).  Always adjust data_offset and
2114 		 * consumed_xmm_halves to make sure TLB flush entries are read
2115 		 * from the correct offset.
2116 		 */
2117 		if (hc->fast)
2118 			hc->consumed_xmm_halves += hc->var_cnt;
2119 		else
2120 			hc->data_offset += hc->var_cnt * sizeof(sparse_banks[0]);
2121 	}
2122 
2123 	if (hc->code == HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE ||
2124 	    hc->code == HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX ||
2125 	    hc->rep_cnt > ARRAY_SIZE(__tlb_flush_entries)) {
2126 		tlb_flush_entries = NULL;
2127 	} else {
2128 		if (kvm_hv_get_tlb_flush_entries(kvm, hc, __tlb_flush_entries))
2129 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
2130 		tlb_flush_entries = __tlb_flush_entries;
2131 	}
2132 
2133 	/*
2134 	 * vcpu->arch.cr3 may not be up-to-date for running vCPUs so we can't
2135 	 * analyze it here, flush TLB regardless of the specified address space.
2136 	 */
2137 	if (all_cpus && !is_guest_mode(vcpu)) {
2138 		kvm_for_each_vcpu(i, v, kvm) {
2139 			tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(v, false);
2140 			hv_tlb_flush_enqueue(v, tlb_flush_fifo,
2141 					     tlb_flush_entries, hc->rep_cnt);
2142 		}
2143 
2144 		kvm_make_all_cpus_request(kvm, KVM_REQ_HV_TLB_FLUSH);
2145 	} else if (!is_guest_mode(vcpu)) {
2146 		sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask, vcpu_mask);
2147 
2148 		for_each_set_bit(i, vcpu_mask, KVM_MAX_VCPUS) {
2149 			v = kvm_get_vcpu(kvm, i);
2150 			if (!v)
2151 				continue;
2152 			tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(v, false);
2153 			hv_tlb_flush_enqueue(v, tlb_flush_fifo,
2154 					     tlb_flush_entries, hc->rep_cnt);
2155 		}
2156 
2157 		kvm_make_vcpus_request_mask(kvm, KVM_REQ_HV_TLB_FLUSH, vcpu_mask);
2158 	} else {
2159 		struct kvm_vcpu_hv *hv_v;
2160 
2161 		bitmap_zero(vcpu_mask, KVM_MAX_VCPUS);
2162 
2163 		kvm_for_each_vcpu(i, v, kvm) {
2164 			hv_v = to_hv_vcpu(v);
2165 
2166 			/*
2167 			 * The following check races with nested vCPUs entering/exiting
2168 			 * and/or migrating between L1's vCPUs, however the only case when
2169 			 * KVM *must* flush the TLB is when the target L2 vCPU keeps
2170 			 * running on the same L1 vCPU from the moment of the request until
2171 			 * kvm_hv_flush_tlb() returns. TLB is fully flushed in all other
2172 			 * cases, e.g. when the target L2 vCPU migrates to a different L1
2173 			 * vCPU or when the corresponding L1 vCPU temporary switches to a
2174 			 * different L2 vCPU while the request is being processed.
2175 			 */
2176 			if (!hv_v || hv_v->nested.vm_id != hv_vcpu->nested.vm_id)
2177 				continue;
2178 
2179 			if (!all_cpus &&
2180 			    !hv_is_vp_in_sparse_set(hv_v->nested.vp_id, valid_bank_mask,
2181 						    sparse_banks))
2182 				continue;
2183 
2184 			__set_bit(i, vcpu_mask);
2185 			tlb_flush_fifo = kvm_hv_get_tlb_flush_fifo(v, true);
2186 			hv_tlb_flush_enqueue(v, tlb_flush_fifo,
2187 					     tlb_flush_entries, hc->rep_cnt);
2188 		}
2189 
2190 		kvm_make_vcpus_request_mask(kvm, KVM_REQ_HV_TLB_FLUSH, vcpu_mask);
2191 	}
2192 
2193 ret_success:
2194 	/* We always do full TLB flush, set 'Reps completed' = 'Rep Count' */
2195 	return (u64)HV_STATUS_SUCCESS |
2196 		((u64)hc->rep_cnt << HV_HYPERCALL_REP_COMP_OFFSET);
2197 }
2198 
kvm_hv_send_ipi_to_many(struct kvm * kvm,u32 vector,u64 * sparse_banks,u64 valid_bank_mask)2199 static void kvm_hv_send_ipi_to_many(struct kvm *kvm, u32 vector,
2200 				    u64 *sparse_banks, u64 valid_bank_mask)
2201 {
2202 	struct kvm_lapic_irq irq = {
2203 		.delivery_mode = APIC_DM_FIXED,
2204 		.vector = vector
2205 	};
2206 	struct kvm_vcpu *vcpu;
2207 	unsigned long i;
2208 
2209 	kvm_for_each_vcpu(i, vcpu, kvm) {
2210 		if (sparse_banks &&
2211 		    !hv_is_vp_in_sparse_set(kvm_hv_get_vpindex(vcpu),
2212 					    valid_bank_mask, sparse_banks))
2213 			continue;
2214 
2215 		/* We fail only when APIC is disabled */
2216 		kvm_apic_set_irq(vcpu, &irq, NULL);
2217 	}
2218 }
2219 
kvm_hv_send_ipi(struct kvm_vcpu * vcpu,struct kvm_hv_hcall * hc)2220 static u64 kvm_hv_send_ipi(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc)
2221 {
2222 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
2223 	u64 *sparse_banks = hv_vcpu->sparse_banks;
2224 	struct kvm *kvm = vcpu->kvm;
2225 	struct hv_send_ipi_ex send_ipi_ex;
2226 	struct hv_send_ipi send_ipi;
2227 	u64 valid_bank_mask;
2228 	u32 vector;
2229 	bool all_cpus;
2230 
2231 	if (!lapic_in_kernel(vcpu))
2232 		return HV_STATUS_INVALID_HYPERCALL_INPUT;
2233 
2234 	if (hc->code == HVCALL_SEND_IPI) {
2235 		if (!hc->fast) {
2236 			if (unlikely(kvm_read_guest(kvm, hc->ingpa, &send_ipi,
2237 						    sizeof(send_ipi))))
2238 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
2239 			sparse_banks[0] = send_ipi.cpu_mask;
2240 			vector = send_ipi.vector;
2241 		} else {
2242 			/* 'reserved' part of hv_send_ipi should be 0 */
2243 			if (unlikely(hc->ingpa >> 32 != 0))
2244 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
2245 			sparse_banks[0] = hc->outgpa;
2246 			vector = (u32)hc->ingpa;
2247 		}
2248 		all_cpus = false;
2249 		valid_bank_mask = BIT_ULL(0);
2250 
2251 		trace_kvm_hv_send_ipi(vector, sparse_banks[0]);
2252 	} else {
2253 		if (!hc->fast) {
2254 			if (unlikely(kvm_read_guest(kvm, hc->ingpa, &send_ipi_ex,
2255 						    sizeof(send_ipi_ex))))
2256 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
2257 		} else {
2258 			send_ipi_ex.vector = (u32)hc->ingpa;
2259 			send_ipi_ex.vp_set.format = hc->outgpa;
2260 			send_ipi_ex.vp_set.valid_bank_mask = sse128_lo(hc->xmm[0]);
2261 		}
2262 
2263 		trace_kvm_hv_send_ipi_ex(send_ipi_ex.vector,
2264 					 send_ipi_ex.vp_set.format,
2265 					 send_ipi_ex.vp_set.valid_bank_mask);
2266 
2267 		vector = send_ipi_ex.vector;
2268 		valid_bank_mask = send_ipi_ex.vp_set.valid_bank_mask;
2269 		all_cpus = send_ipi_ex.vp_set.format == HV_GENERIC_SET_ALL;
2270 
2271 		if (hc->var_cnt != hweight64(valid_bank_mask))
2272 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
2273 
2274 		if (all_cpus)
2275 			goto check_and_send_ipi;
2276 
2277 		if (!hc->var_cnt)
2278 			goto ret_success;
2279 
2280 		if (!hc->fast)
2281 			hc->data_offset = offsetof(struct hv_send_ipi_ex,
2282 						   vp_set.bank_contents);
2283 		else
2284 			hc->consumed_xmm_halves = 1;
2285 
2286 		if (kvm_get_sparse_vp_set(kvm, hc, sparse_banks))
2287 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
2288 	}
2289 
2290 check_and_send_ipi:
2291 	if ((vector < HV_IPI_LOW_VECTOR) || (vector > HV_IPI_HIGH_VECTOR))
2292 		return HV_STATUS_INVALID_HYPERCALL_INPUT;
2293 
2294 	if (all_cpus)
2295 		kvm_hv_send_ipi_to_many(kvm, vector, NULL, 0);
2296 	else
2297 		kvm_hv_send_ipi_to_many(kvm, vector, sparse_banks, valid_bank_mask);
2298 
2299 ret_success:
2300 	return HV_STATUS_SUCCESS;
2301 }
2302 
kvm_hv_set_cpuid(struct kvm_vcpu * vcpu,bool hyperv_enabled)2303 void kvm_hv_set_cpuid(struct kvm_vcpu *vcpu, bool hyperv_enabled)
2304 {
2305 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
2306 	struct kvm_cpuid_entry2 *entry;
2307 
2308 	vcpu->arch.hyperv_enabled = hyperv_enabled;
2309 
2310 	if (!hv_vcpu) {
2311 		/*
2312 		 * KVM should have already allocated kvm_vcpu_hv if Hyper-V is
2313 		 * enabled in CPUID.
2314 		 */
2315 		WARN_ON_ONCE(vcpu->arch.hyperv_enabled);
2316 		return;
2317 	}
2318 
2319 	memset(&hv_vcpu->cpuid_cache, 0, sizeof(hv_vcpu->cpuid_cache));
2320 
2321 	if (!vcpu->arch.hyperv_enabled)
2322 		return;
2323 
2324 	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_FEATURES);
2325 	if (entry) {
2326 		hv_vcpu->cpuid_cache.features_eax = entry->eax;
2327 		hv_vcpu->cpuid_cache.features_ebx = entry->ebx;
2328 		hv_vcpu->cpuid_cache.features_edx = entry->edx;
2329 	}
2330 
2331 	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_ENLIGHTMENT_INFO);
2332 	if (entry) {
2333 		hv_vcpu->cpuid_cache.enlightenments_eax = entry->eax;
2334 		hv_vcpu->cpuid_cache.enlightenments_ebx = entry->ebx;
2335 	}
2336 
2337 	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES);
2338 	if (entry)
2339 		hv_vcpu->cpuid_cache.syndbg_cap_eax = entry->eax;
2340 
2341 	entry = kvm_find_cpuid_entry(vcpu, HYPERV_CPUID_NESTED_FEATURES);
2342 	if (entry) {
2343 		hv_vcpu->cpuid_cache.nested_eax = entry->eax;
2344 		hv_vcpu->cpuid_cache.nested_ebx = entry->ebx;
2345 	}
2346 }
2347 
kvm_hv_set_enforce_cpuid(struct kvm_vcpu * vcpu,bool enforce)2348 int kvm_hv_set_enforce_cpuid(struct kvm_vcpu *vcpu, bool enforce)
2349 {
2350 	struct kvm_vcpu_hv *hv_vcpu;
2351 	int ret = 0;
2352 
2353 	if (!to_hv_vcpu(vcpu)) {
2354 		if (enforce) {
2355 			ret = kvm_hv_vcpu_init(vcpu);
2356 			if (ret)
2357 				return ret;
2358 		} else {
2359 			return 0;
2360 		}
2361 	}
2362 
2363 	hv_vcpu = to_hv_vcpu(vcpu);
2364 	hv_vcpu->enforce_cpuid = enforce;
2365 
2366 	return ret;
2367 }
2368 
kvm_hv_hypercall_set_result(struct kvm_vcpu * vcpu,u64 result)2369 static void kvm_hv_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)
2370 {
2371 	bool longmode;
2372 
2373 	longmode = is_64_bit_hypercall(vcpu);
2374 	if (longmode)
2375 		kvm_rax_write(vcpu, result);
2376 	else {
2377 		kvm_rdx_write(vcpu, result >> 32);
2378 		kvm_rax_write(vcpu, result & 0xffffffff);
2379 	}
2380 }
2381 
kvm_hv_hypercall_complete(struct kvm_vcpu * vcpu,u64 result)2382 static int kvm_hv_hypercall_complete(struct kvm_vcpu *vcpu, u64 result)
2383 {
2384 	u32 tlb_lock_count = 0;
2385 	int ret;
2386 
2387 	if (hv_result_success(result) && is_guest_mode(vcpu) &&
2388 	    kvm_hv_is_tlb_flush_hcall(vcpu) &&
2389 	    kvm_read_guest(vcpu->kvm, to_hv_vcpu(vcpu)->nested.pa_page_gpa,
2390 			   &tlb_lock_count, sizeof(tlb_lock_count)))
2391 		result = HV_STATUS_INVALID_HYPERCALL_INPUT;
2392 
2393 	trace_kvm_hv_hypercall_done(result);
2394 	kvm_hv_hypercall_set_result(vcpu, result);
2395 	++vcpu->stat.hypercalls;
2396 
2397 	ret = kvm_skip_emulated_instruction(vcpu);
2398 
2399 	if (tlb_lock_count)
2400 		kvm_x86_ops.nested_ops->hv_inject_synthetic_vmexit_post_tlb_flush(vcpu);
2401 
2402 	return ret;
2403 }
2404 
kvm_hv_hypercall_complete_userspace(struct kvm_vcpu * vcpu)2405 static int kvm_hv_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
2406 {
2407 	return kvm_hv_hypercall_complete(vcpu, vcpu->run->hyperv.u.hcall.result);
2408 }
2409 
kvm_hvcall_signal_event(struct kvm_vcpu * vcpu,struct kvm_hv_hcall * hc)2410 static u16 kvm_hvcall_signal_event(struct kvm_vcpu *vcpu, struct kvm_hv_hcall *hc)
2411 {
2412 	struct kvm_hv *hv = to_kvm_hv(vcpu->kvm);
2413 	struct eventfd_ctx *eventfd;
2414 
2415 	if (unlikely(!hc->fast)) {
2416 		int ret;
2417 		gpa_t gpa = hc->ingpa;
2418 
2419 		if ((gpa & (__alignof__(hc->ingpa) - 1)) ||
2420 		    offset_in_page(gpa) + sizeof(hc->ingpa) > PAGE_SIZE)
2421 			return HV_STATUS_INVALID_ALIGNMENT;
2422 
2423 		ret = kvm_vcpu_read_guest(vcpu, gpa,
2424 					  &hc->ingpa, sizeof(hc->ingpa));
2425 		if (ret < 0)
2426 			return HV_STATUS_INVALID_ALIGNMENT;
2427 	}
2428 
2429 	/*
2430 	 * Per spec, bits 32-47 contain the extra "flag number".  However, we
2431 	 * have no use for it, and in all known usecases it is zero, so just
2432 	 * report lookup failure if it isn't.
2433 	 */
2434 	if (hc->ingpa & 0xffff00000000ULL)
2435 		return HV_STATUS_INVALID_PORT_ID;
2436 	/* remaining bits are reserved-zero */
2437 	if (hc->ingpa & ~KVM_HYPERV_CONN_ID_MASK)
2438 		return HV_STATUS_INVALID_HYPERCALL_INPUT;
2439 
2440 	/* the eventfd is protected by vcpu->kvm->srcu, but conn_to_evt isn't */
2441 	rcu_read_lock();
2442 	eventfd = idr_find(&hv->conn_to_evt, hc->ingpa);
2443 	rcu_read_unlock();
2444 	if (!eventfd)
2445 		return HV_STATUS_INVALID_PORT_ID;
2446 
2447 	eventfd_signal(eventfd);
2448 	return HV_STATUS_SUCCESS;
2449 }
2450 
is_xmm_fast_hypercall(struct kvm_hv_hcall * hc)2451 static bool is_xmm_fast_hypercall(struct kvm_hv_hcall *hc)
2452 {
2453 	switch (hc->code) {
2454 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST:
2455 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE:
2456 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST_EX:
2457 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX:
2458 	case HVCALL_SEND_IPI_EX:
2459 		return true;
2460 	}
2461 
2462 	return false;
2463 }
2464 
kvm_hv_hypercall_read_xmm(struct kvm_hv_hcall * hc)2465 static void kvm_hv_hypercall_read_xmm(struct kvm_hv_hcall *hc)
2466 {
2467 	int reg;
2468 
2469 	kvm_fpu_get();
2470 	for (reg = 0; reg < HV_HYPERCALL_MAX_XMM_REGISTERS; reg++)
2471 		_kvm_read_sse_reg(reg, &hc->xmm[reg]);
2472 	kvm_fpu_put();
2473 }
2474 
hv_check_hypercall_access(struct kvm_vcpu_hv * hv_vcpu,u16 code)2475 static bool hv_check_hypercall_access(struct kvm_vcpu_hv *hv_vcpu, u16 code)
2476 {
2477 	if (!hv_vcpu->enforce_cpuid)
2478 		return true;
2479 
2480 	switch (code) {
2481 	case HVCALL_NOTIFY_LONG_SPIN_WAIT:
2482 		return hv_vcpu->cpuid_cache.enlightenments_ebx &&
2483 			hv_vcpu->cpuid_cache.enlightenments_ebx != U32_MAX;
2484 	case HVCALL_POST_MESSAGE:
2485 		return hv_vcpu->cpuid_cache.features_ebx & HV_POST_MESSAGES;
2486 	case HVCALL_SIGNAL_EVENT:
2487 		return hv_vcpu->cpuid_cache.features_ebx & HV_SIGNAL_EVENTS;
2488 	case HVCALL_POST_DEBUG_DATA:
2489 	case HVCALL_RETRIEVE_DEBUG_DATA:
2490 	case HVCALL_RESET_DEBUG_SESSION:
2491 		/*
2492 		 * Return 'true' when SynDBG is disabled so the resulting code
2493 		 * will be HV_STATUS_INVALID_HYPERCALL_CODE.
2494 		 */
2495 		return !kvm_hv_is_syndbg_enabled(hv_vcpu->vcpu) ||
2496 			hv_vcpu->cpuid_cache.features_ebx & HV_DEBUGGING;
2497 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST_EX:
2498 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX:
2499 		if (!(hv_vcpu->cpuid_cache.enlightenments_eax &
2500 		      HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED))
2501 			return false;
2502 		fallthrough;
2503 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST:
2504 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE:
2505 		return hv_vcpu->cpuid_cache.enlightenments_eax &
2506 			HV_X64_REMOTE_TLB_FLUSH_RECOMMENDED;
2507 	case HVCALL_SEND_IPI_EX:
2508 		if (!(hv_vcpu->cpuid_cache.enlightenments_eax &
2509 		      HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED))
2510 			return false;
2511 		fallthrough;
2512 	case HVCALL_SEND_IPI:
2513 		return hv_vcpu->cpuid_cache.enlightenments_eax &
2514 			HV_X64_CLUSTER_IPI_RECOMMENDED;
2515 	case HV_EXT_CALL_QUERY_CAPABILITIES ... HV_EXT_CALL_MAX:
2516 		return hv_vcpu->cpuid_cache.features_ebx &
2517 			HV_ENABLE_EXTENDED_HYPERCALLS;
2518 	default:
2519 		break;
2520 	}
2521 
2522 	return true;
2523 }
2524 
kvm_hv_hypercall(struct kvm_vcpu * vcpu)2525 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
2526 {
2527 	struct kvm_vcpu_hv *hv_vcpu = to_hv_vcpu(vcpu);
2528 	struct kvm_hv_hcall hc;
2529 	u64 ret = HV_STATUS_SUCCESS;
2530 
2531 	/*
2532 	 * hypercall generates UD from non zero cpl and real mode
2533 	 * per HYPER-V spec
2534 	 */
2535 	if (kvm_x86_call(get_cpl)(vcpu) != 0 || !is_protmode(vcpu)) {
2536 		kvm_queue_exception(vcpu, UD_VECTOR);
2537 		return 1;
2538 	}
2539 
2540 #ifdef CONFIG_X86_64
2541 	if (is_64_bit_hypercall(vcpu)) {
2542 		hc.param = kvm_rcx_read(vcpu);
2543 		hc.ingpa = kvm_rdx_read(vcpu);
2544 		hc.outgpa = kvm_r8_read(vcpu);
2545 	} else
2546 #endif
2547 	{
2548 		hc.param = ((u64)kvm_rdx_read(vcpu) << 32) |
2549 			    (kvm_rax_read(vcpu) & 0xffffffff);
2550 		hc.ingpa = ((u64)kvm_rbx_read(vcpu) << 32) |
2551 			    (kvm_rcx_read(vcpu) & 0xffffffff);
2552 		hc.outgpa = ((u64)kvm_rdi_read(vcpu) << 32) |
2553 			     (kvm_rsi_read(vcpu) & 0xffffffff);
2554 	}
2555 
2556 	hc.code = hc.param & 0xffff;
2557 	hc.var_cnt = (hc.param & HV_HYPERCALL_VARHEAD_MASK) >> HV_HYPERCALL_VARHEAD_OFFSET;
2558 	hc.fast = !!(hc.param & HV_HYPERCALL_FAST_BIT);
2559 	hc.rep_cnt = (hc.param >> HV_HYPERCALL_REP_COMP_OFFSET) & 0xfff;
2560 	hc.rep_idx = (hc.param >> HV_HYPERCALL_REP_START_OFFSET) & 0xfff;
2561 	hc.rep = !!(hc.rep_cnt || hc.rep_idx);
2562 
2563 	trace_kvm_hv_hypercall(hc.code, hc.fast, hc.var_cnt, hc.rep_cnt,
2564 			       hc.rep_idx, hc.ingpa, hc.outgpa);
2565 
2566 	if (unlikely(!hv_check_hypercall_access(hv_vcpu, hc.code))) {
2567 		ret = HV_STATUS_ACCESS_DENIED;
2568 		goto hypercall_complete;
2569 	}
2570 
2571 	if (unlikely(hc.param & HV_HYPERCALL_RSVD_MASK)) {
2572 		ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2573 		goto hypercall_complete;
2574 	}
2575 
2576 	if (hc.fast && is_xmm_fast_hypercall(&hc)) {
2577 		if (unlikely(hv_vcpu->enforce_cpuid &&
2578 			     !(hv_vcpu->cpuid_cache.features_edx &
2579 			       HV_X64_HYPERCALL_XMM_INPUT_AVAILABLE))) {
2580 			kvm_queue_exception(vcpu, UD_VECTOR);
2581 			return 1;
2582 		}
2583 
2584 		kvm_hv_hypercall_read_xmm(&hc);
2585 	}
2586 
2587 	switch (hc.code) {
2588 	case HVCALL_NOTIFY_LONG_SPIN_WAIT:
2589 		if (unlikely(hc.rep || hc.var_cnt)) {
2590 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2591 			break;
2592 		}
2593 		kvm_vcpu_on_spin(vcpu, true);
2594 		break;
2595 	case HVCALL_SIGNAL_EVENT:
2596 		if (unlikely(hc.rep || hc.var_cnt)) {
2597 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2598 			break;
2599 		}
2600 		ret = kvm_hvcall_signal_event(vcpu, &hc);
2601 		if (ret != HV_STATUS_INVALID_PORT_ID)
2602 			break;
2603 		fallthrough;	/* maybe userspace knows this conn_id */
2604 	case HVCALL_POST_MESSAGE:
2605 		/* don't bother userspace if it has no way to handle it */
2606 		if (unlikely(hc.rep || hc.var_cnt || !to_hv_synic(vcpu)->active)) {
2607 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2608 			break;
2609 		}
2610 		goto hypercall_userspace_exit;
2611 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST:
2612 		if (unlikely(hc.var_cnt)) {
2613 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2614 			break;
2615 		}
2616 		fallthrough;
2617 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST_EX:
2618 		if (unlikely(!hc.rep_cnt || hc.rep_idx)) {
2619 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2620 			break;
2621 		}
2622 		ret = kvm_hv_flush_tlb(vcpu, &hc);
2623 		break;
2624 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE:
2625 		if (unlikely(hc.var_cnt)) {
2626 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2627 			break;
2628 		}
2629 		fallthrough;
2630 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX:
2631 		if (unlikely(hc.rep)) {
2632 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2633 			break;
2634 		}
2635 		ret = kvm_hv_flush_tlb(vcpu, &hc);
2636 		break;
2637 	case HVCALL_SEND_IPI:
2638 		if (unlikely(hc.var_cnt)) {
2639 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2640 			break;
2641 		}
2642 		fallthrough;
2643 	case HVCALL_SEND_IPI_EX:
2644 		if (unlikely(hc.rep)) {
2645 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
2646 			break;
2647 		}
2648 		ret = kvm_hv_send_ipi(vcpu, &hc);
2649 		break;
2650 	case HVCALL_POST_DEBUG_DATA:
2651 	case HVCALL_RETRIEVE_DEBUG_DATA:
2652 		if (unlikely(hc.fast)) {
2653 			ret = HV_STATUS_INVALID_PARAMETER;
2654 			break;
2655 		}
2656 		fallthrough;
2657 	case HVCALL_RESET_DEBUG_SESSION: {
2658 		struct kvm_hv_syndbg *syndbg = to_hv_syndbg(vcpu);
2659 
2660 		if (!kvm_hv_is_syndbg_enabled(vcpu)) {
2661 			ret = HV_STATUS_INVALID_HYPERCALL_CODE;
2662 			break;
2663 		}
2664 
2665 		if (!(syndbg->options & HV_X64_SYNDBG_OPTION_USE_HCALLS)) {
2666 			ret = HV_STATUS_OPERATION_DENIED;
2667 			break;
2668 		}
2669 		goto hypercall_userspace_exit;
2670 	}
2671 	case HV_EXT_CALL_QUERY_CAPABILITIES ... HV_EXT_CALL_MAX:
2672 		if (unlikely(hc.fast)) {
2673 			ret = HV_STATUS_INVALID_PARAMETER;
2674 			break;
2675 		}
2676 		goto hypercall_userspace_exit;
2677 	default:
2678 		ret = HV_STATUS_INVALID_HYPERCALL_CODE;
2679 		break;
2680 	}
2681 
2682 hypercall_complete:
2683 	return kvm_hv_hypercall_complete(vcpu, ret);
2684 
2685 hypercall_userspace_exit:
2686 	vcpu->run->exit_reason = KVM_EXIT_HYPERV;
2687 	vcpu->run->hyperv.type = KVM_EXIT_HYPERV_HCALL;
2688 	vcpu->run->hyperv.u.hcall.input = hc.param;
2689 	vcpu->run->hyperv.u.hcall.params[0] = hc.ingpa;
2690 	vcpu->run->hyperv.u.hcall.params[1] = hc.outgpa;
2691 	vcpu->arch.complete_userspace_io = kvm_hv_hypercall_complete_userspace;
2692 	return 0;
2693 }
2694 
kvm_hv_init_vm(struct kvm * kvm)2695 void kvm_hv_init_vm(struct kvm *kvm)
2696 {
2697 	struct kvm_hv *hv = to_kvm_hv(kvm);
2698 
2699 	mutex_init(&hv->hv_lock);
2700 	idr_init(&hv->conn_to_evt);
2701 }
2702 
kvm_hv_destroy_vm(struct kvm * kvm)2703 void kvm_hv_destroy_vm(struct kvm *kvm)
2704 {
2705 	struct kvm_hv *hv = to_kvm_hv(kvm);
2706 	struct eventfd_ctx *eventfd;
2707 	int i;
2708 
2709 	idr_for_each_entry(&hv->conn_to_evt, eventfd, i)
2710 		eventfd_ctx_put(eventfd);
2711 	idr_destroy(&hv->conn_to_evt);
2712 }
2713 
kvm_hv_eventfd_assign(struct kvm * kvm,u32 conn_id,int fd)2714 static int kvm_hv_eventfd_assign(struct kvm *kvm, u32 conn_id, int fd)
2715 {
2716 	struct kvm_hv *hv = to_kvm_hv(kvm);
2717 	struct eventfd_ctx *eventfd;
2718 	int ret;
2719 
2720 	eventfd = eventfd_ctx_fdget(fd);
2721 	if (IS_ERR(eventfd))
2722 		return PTR_ERR(eventfd);
2723 
2724 	mutex_lock(&hv->hv_lock);
2725 	ret = idr_alloc(&hv->conn_to_evt, eventfd, conn_id, conn_id + 1,
2726 			GFP_KERNEL_ACCOUNT);
2727 	mutex_unlock(&hv->hv_lock);
2728 
2729 	if (ret >= 0)
2730 		return 0;
2731 
2732 	if (ret == -ENOSPC)
2733 		ret = -EEXIST;
2734 	eventfd_ctx_put(eventfd);
2735 	return ret;
2736 }
2737 
kvm_hv_eventfd_deassign(struct kvm * kvm,u32 conn_id)2738 static int kvm_hv_eventfd_deassign(struct kvm *kvm, u32 conn_id)
2739 {
2740 	struct kvm_hv *hv = to_kvm_hv(kvm);
2741 	struct eventfd_ctx *eventfd;
2742 
2743 	mutex_lock(&hv->hv_lock);
2744 	eventfd = idr_remove(&hv->conn_to_evt, conn_id);
2745 	mutex_unlock(&hv->hv_lock);
2746 
2747 	if (!eventfd)
2748 		return -ENOENT;
2749 
2750 	synchronize_srcu(&kvm->srcu);
2751 	eventfd_ctx_put(eventfd);
2752 	return 0;
2753 }
2754 
kvm_vm_ioctl_hv_eventfd(struct kvm * kvm,struct kvm_hyperv_eventfd * args)2755 int kvm_vm_ioctl_hv_eventfd(struct kvm *kvm, struct kvm_hyperv_eventfd *args)
2756 {
2757 	if ((args->flags & ~KVM_HYPERV_EVENTFD_DEASSIGN) ||
2758 	    (args->conn_id & ~KVM_HYPERV_CONN_ID_MASK))
2759 		return -EINVAL;
2760 
2761 	if (args->flags == KVM_HYPERV_EVENTFD_DEASSIGN)
2762 		return kvm_hv_eventfd_deassign(kvm, args->conn_id);
2763 	return kvm_hv_eventfd_assign(kvm, args->conn_id, args->fd);
2764 }
2765 
kvm_get_hv_cpuid(struct kvm_vcpu * vcpu,struct kvm_cpuid2 * cpuid,struct kvm_cpuid_entry2 __user * entries)2766 int kvm_get_hv_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid2 *cpuid,
2767 		     struct kvm_cpuid_entry2 __user *entries)
2768 {
2769 	uint16_t evmcs_ver = 0;
2770 	struct kvm_cpuid_entry2 cpuid_entries[] = {
2771 		{ .function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS },
2772 		{ .function = HYPERV_CPUID_INTERFACE },
2773 		{ .function = HYPERV_CPUID_VERSION },
2774 		{ .function = HYPERV_CPUID_FEATURES },
2775 		{ .function = HYPERV_CPUID_ENLIGHTMENT_INFO },
2776 		{ .function = HYPERV_CPUID_IMPLEMENT_LIMITS },
2777 		{ .function = HYPERV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS },
2778 		{ .function = HYPERV_CPUID_SYNDBG_INTERFACE },
2779 		{ .function = HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES	},
2780 		{ .function = HYPERV_CPUID_NESTED_FEATURES },
2781 	};
2782 	int i, nent = ARRAY_SIZE(cpuid_entries);
2783 
2784 	if (kvm_x86_ops.nested_ops->get_evmcs_version)
2785 		evmcs_ver = kvm_x86_ops.nested_ops->get_evmcs_version(vcpu);
2786 
2787 	if (cpuid->nent < nent)
2788 		return -E2BIG;
2789 
2790 	if (cpuid->nent > nent)
2791 		cpuid->nent = nent;
2792 
2793 	for (i = 0; i < nent; i++) {
2794 		struct kvm_cpuid_entry2 *ent = &cpuid_entries[i];
2795 		u32 signature[3];
2796 
2797 		switch (ent->function) {
2798 		case HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS:
2799 			memcpy(signature, "Linux KVM Hv", 12);
2800 
2801 			ent->eax = HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES;
2802 			ent->ebx = signature[0];
2803 			ent->ecx = signature[1];
2804 			ent->edx = signature[2];
2805 			break;
2806 
2807 		case HYPERV_CPUID_INTERFACE:
2808 			ent->eax = HYPERV_CPUID_SIGNATURE_EAX;
2809 			break;
2810 
2811 		case HYPERV_CPUID_VERSION:
2812 			/*
2813 			 * We implement some Hyper-V 2016 functions so let's use
2814 			 * this version.
2815 			 */
2816 			ent->eax = 0x00003839;
2817 			ent->ebx = 0x000A0000;
2818 			break;
2819 
2820 		case HYPERV_CPUID_FEATURES:
2821 			ent->eax |= HV_MSR_VP_RUNTIME_AVAILABLE;
2822 			ent->eax |= HV_MSR_TIME_REF_COUNT_AVAILABLE;
2823 			ent->eax |= HV_MSR_SYNIC_AVAILABLE;
2824 			ent->eax |= HV_MSR_SYNTIMER_AVAILABLE;
2825 			ent->eax |= HV_MSR_APIC_ACCESS_AVAILABLE;
2826 			ent->eax |= HV_MSR_HYPERCALL_AVAILABLE;
2827 			ent->eax |= HV_MSR_VP_INDEX_AVAILABLE;
2828 			ent->eax |= HV_MSR_RESET_AVAILABLE;
2829 			ent->eax |= HV_MSR_REFERENCE_TSC_AVAILABLE;
2830 			ent->eax |= HV_ACCESS_FREQUENCY_MSRS;
2831 			ent->eax |= HV_ACCESS_REENLIGHTENMENT;
2832 			ent->eax |= HV_ACCESS_TSC_INVARIANT;
2833 
2834 			ent->ebx |= HV_POST_MESSAGES;
2835 			ent->ebx |= HV_SIGNAL_EVENTS;
2836 			ent->ebx |= HV_ENABLE_EXTENDED_HYPERCALLS;
2837 
2838 			ent->edx |= HV_X64_HYPERCALL_XMM_INPUT_AVAILABLE;
2839 			ent->edx |= HV_FEATURE_FREQUENCY_MSRS_AVAILABLE;
2840 			ent->edx |= HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE;
2841 
2842 			ent->ebx |= HV_DEBUGGING;
2843 			ent->edx |= HV_X64_GUEST_DEBUGGING_AVAILABLE;
2844 			ent->edx |= HV_FEATURE_DEBUG_MSRS_AVAILABLE;
2845 			ent->edx |= HV_FEATURE_EXT_GVA_RANGES_FLUSH;
2846 
2847 			/*
2848 			 * Direct Synthetic timers only make sense with in-kernel
2849 			 * LAPIC
2850 			 */
2851 			if (!vcpu || lapic_in_kernel(vcpu))
2852 				ent->edx |= HV_STIMER_DIRECT_MODE_AVAILABLE;
2853 
2854 			break;
2855 
2856 		case HYPERV_CPUID_ENLIGHTMENT_INFO:
2857 			ent->eax |= HV_X64_REMOTE_TLB_FLUSH_RECOMMENDED;
2858 			ent->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
2859 			ent->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
2860 			if (!vcpu || lapic_in_kernel(vcpu))
2861 				ent->eax |= HV_X64_CLUSTER_IPI_RECOMMENDED;
2862 			ent->eax |= HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED;
2863 			if (evmcs_ver)
2864 				ent->eax |= HV_X64_ENLIGHTENED_VMCS_RECOMMENDED;
2865 			if (!cpu_smt_possible())
2866 				ent->eax |= HV_X64_NO_NONARCH_CORESHARING;
2867 
2868 			ent->eax |= HV_DEPRECATING_AEOI_RECOMMENDED;
2869 			/*
2870 			 * Default number of spinlock retry attempts, matches
2871 			 * HyperV 2016.
2872 			 */
2873 			ent->ebx = 0x00000FFF;
2874 
2875 			break;
2876 
2877 		case HYPERV_CPUID_IMPLEMENT_LIMITS:
2878 			/* Maximum number of virtual processors */
2879 			ent->eax = KVM_MAX_VCPUS;
2880 			/*
2881 			 * Maximum number of logical processors, matches
2882 			 * HyperV 2016.
2883 			 */
2884 			ent->ebx = 64;
2885 
2886 			break;
2887 
2888 		case HYPERV_CPUID_NESTED_FEATURES:
2889 			ent->eax = evmcs_ver;
2890 			ent->eax |= HV_X64_NESTED_DIRECT_FLUSH;
2891 			ent->eax |= HV_X64_NESTED_MSR_BITMAP;
2892 			ent->ebx |= HV_X64_NESTED_EVMCS1_PERF_GLOBAL_CTRL;
2893 			break;
2894 
2895 		case HYPERV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS:
2896 			memcpy(signature, "Linux KVM Hv", 12);
2897 
2898 			ent->eax = 0;
2899 			ent->ebx = signature[0];
2900 			ent->ecx = signature[1];
2901 			ent->edx = signature[2];
2902 			break;
2903 
2904 		case HYPERV_CPUID_SYNDBG_INTERFACE:
2905 			memcpy(signature, "VS#1\0\0\0\0\0\0\0\0", 12);
2906 			ent->eax = signature[0];
2907 			break;
2908 
2909 		case HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES:
2910 			ent->eax |= HV_X64_SYNDBG_CAP_ALLOW_KERNEL_DEBUGGING;
2911 			break;
2912 
2913 		default:
2914 			break;
2915 		}
2916 	}
2917 
2918 	if (copy_to_user(entries, cpuid_entries,
2919 			 nent * sizeof(struct kvm_cpuid_entry2)))
2920 		return -EFAULT;
2921 
2922 	return 0;
2923 }
2924