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