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