xref: /openbmc/linux/arch/x86/kvm/hyperv.c (revision ae40e94f)
1 /*
2  * KVM Microsoft Hyper-V emulation
3  *
4  * derived from arch/x86/kvm/x86.c
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2008 Qumranet, Inc.
8  * Copyright IBM Corporation, 2008
9  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10  * Copyright (C) 2015 Andrey Smetanin <asmetanin@virtuozzo.com>
11  *
12  * Authors:
13  *   Avi Kivity   <avi@qumranet.com>
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Amit Shah    <amit.shah@qumranet.com>
16  *   Ben-Ami Yassour <benami@il.ibm.com>
17  *   Andrey Smetanin <asmetanin@virtuozzo.com>
18  *
19  * This work is licensed under the terms of the GNU GPL, version 2.  See
20  * the COPYING file in the top-level directory.
21  *
22  */
23 
24 #include "x86.h"
25 #include "lapic.h"
26 #include "ioapic.h"
27 #include "hyperv.h"
28 
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 
39 #define KVM_HV_MAX_SPARSE_VCPU_SET_BITS DIV_ROUND_UP(KVM_MAX_VCPUS, 64)
40 
41 static void stimer_mark_pending(struct kvm_vcpu_hv_stimer *stimer,
42 				bool vcpu_kick);
43 
44 static inline u64 synic_read_sint(struct kvm_vcpu_hv_synic *synic, int sint)
45 {
46 	return atomic64_read(&synic->sint[sint]);
47 }
48 
49 static inline int synic_get_sint_vector(u64 sint_value)
50 {
51 	if (sint_value & HV_SYNIC_SINT_MASKED)
52 		return -1;
53 	return sint_value & HV_SYNIC_SINT_VECTOR_MASK;
54 }
55 
56 static bool synic_has_vector_connected(struct kvm_vcpu_hv_synic *synic,
57 				      int vector)
58 {
59 	int i;
60 
61 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
62 		if (synic_get_sint_vector(synic_read_sint(synic, i)) == vector)
63 			return true;
64 	}
65 	return false;
66 }
67 
68 static bool synic_has_vector_auto_eoi(struct kvm_vcpu_hv_synic *synic,
69 				     int vector)
70 {
71 	int i;
72 	u64 sint_value;
73 
74 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
75 		sint_value = synic_read_sint(synic, i);
76 		if (synic_get_sint_vector(sint_value) == vector &&
77 		    sint_value & HV_SYNIC_SINT_AUTO_EOI)
78 			return true;
79 	}
80 	return false;
81 }
82 
83 static void synic_update_vector(struct kvm_vcpu_hv_synic *synic,
84 				int vector)
85 {
86 	if (vector < HV_SYNIC_FIRST_VALID_VECTOR)
87 		return;
88 
89 	if (synic_has_vector_connected(synic, vector))
90 		__set_bit(vector, synic->vec_bitmap);
91 	else
92 		__clear_bit(vector, synic->vec_bitmap);
93 
94 	if (synic_has_vector_auto_eoi(synic, vector))
95 		__set_bit(vector, synic->auto_eoi_bitmap);
96 	else
97 		__clear_bit(vector, synic->auto_eoi_bitmap);
98 }
99 
100 static int synic_set_sint(struct kvm_vcpu_hv_synic *synic, int sint,
101 			  u64 data, bool host)
102 {
103 	int vector, old_vector;
104 	bool masked;
105 
106 	vector = data & HV_SYNIC_SINT_VECTOR_MASK;
107 	masked = data & HV_SYNIC_SINT_MASKED;
108 
109 	/*
110 	 * Valid vectors are 16-255, however, nested Hyper-V attempts to write
111 	 * default '0x10000' value on boot and this should not #GP. We need to
112 	 * allow zero-initing the register from host as well.
113 	 */
114 	if (vector < HV_SYNIC_FIRST_VALID_VECTOR && !host && !masked)
115 		return 1;
116 	/*
117 	 * Guest may configure multiple SINTs to use the same vector, so
118 	 * we maintain a bitmap of vectors handled by synic, and a
119 	 * bitmap of vectors with auto-eoi behavior.  The bitmaps are
120 	 * updated here, and atomically queried on fast paths.
121 	 */
122 	old_vector = synic_read_sint(synic, sint) & HV_SYNIC_SINT_VECTOR_MASK;
123 
124 	atomic64_set(&synic->sint[sint], data);
125 
126 	synic_update_vector(synic, old_vector);
127 
128 	synic_update_vector(synic, vector);
129 
130 	/* Load SynIC vectors into EOI exit bitmap */
131 	kvm_make_request(KVM_REQ_SCAN_IOAPIC, synic_to_vcpu(synic));
132 	return 0;
133 }
134 
135 static struct kvm_vcpu *get_vcpu_by_vpidx(struct kvm *kvm, u32 vpidx)
136 {
137 	struct kvm_vcpu *vcpu = NULL;
138 	int i;
139 
140 	if (vpidx >= KVM_MAX_VCPUS)
141 		return NULL;
142 
143 	vcpu = kvm_get_vcpu(kvm, vpidx);
144 	if (vcpu && vcpu_to_hv_vcpu(vcpu)->vp_index == vpidx)
145 		return vcpu;
146 	kvm_for_each_vcpu(i, vcpu, kvm)
147 		if (vcpu_to_hv_vcpu(vcpu)->vp_index == vpidx)
148 			return vcpu;
149 	return NULL;
150 }
151 
152 static struct kvm_vcpu_hv_synic *synic_get(struct kvm *kvm, u32 vpidx)
153 {
154 	struct kvm_vcpu *vcpu;
155 	struct kvm_vcpu_hv_synic *synic;
156 
157 	vcpu = get_vcpu_by_vpidx(kvm, vpidx);
158 	if (!vcpu)
159 		return NULL;
160 	synic = vcpu_to_synic(vcpu);
161 	return (synic->active) ? synic : NULL;
162 }
163 
164 static void kvm_hv_notify_acked_sint(struct kvm_vcpu *vcpu, u32 sint)
165 {
166 	struct kvm *kvm = vcpu->kvm;
167 	struct kvm_vcpu_hv_synic *synic = vcpu_to_synic(vcpu);
168 	struct kvm_vcpu_hv *hv_vcpu = vcpu_to_hv_vcpu(vcpu);
169 	struct kvm_vcpu_hv_stimer *stimer;
170 	int gsi, idx;
171 
172 	trace_kvm_hv_notify_acked_sint(vcpu->vcpu_id, sint);
173 
174 	/* Try to deliver pending Hyper-V SynIC timers messages */
175 	for (idx = 0; idx < ARRAY_SIZE(hv_vcpu->stimer); idx++) {
176 		stimer = &hv_vcpu->stimer[idx];
177 		if (stimer->msg_pending && stimer->config.enable &&
178 		    !stimer->config.direct_mode &&
179 		    stimer->config.sintx == sint)
180 			stimer_mark_pending(stimer, false);
181 	}
182 
183 	idx = srcu_read_lock(&kvm->irq_srcu);
184 	gsi = atomic_read(&synic->sint_to_gsi[sint]);
185 	if (gsi != -1)
186 		kvm_notify_acked_gsi(kvm, gsi);
187 	srcu_read_unlock(&kvm->irq_srcu, idx);
188 }
189 
190 static void synic_exit(struct kvm_vcpu_hv_synic *synic, u32 msr)
191 {
192 	struct kvm_vcpu *vcpu = synic_to_vcpu(synic);
193 	struct kvm_vcpu_hv *hv_vcpu = &vcpu->arch.hyperv;
194 
195 	hv_vcpu->exit.type = KVM_EXIT_HYPERV_SYNIC;
196 	hv_vcpu->exit.u.synic.msr = msr;
197 	hv_vcpu->exit.u.synic.control = synic->control;
198 	hv_vcpu->exit.u.synic.evt_page = synic->evt_page;
199 	hv_vcpu->exit.u.synic.msg_page = synic->msg_page;
200 
201 	kvm_make_request(KVM_REQ_HV_EXIT, vcpu);
202 }
203 
204 static int synic_set_msr(struct kvm_vcpu_hv_synic *synic,
205 			 u32 msr, u64 data, bool host)
206 {
207 	struct kvm_vcpu *vcpu = synic_to_vcpu(synic);
208 	int ret;
209 
210 	if (!synic->active && !host)
211 		return 1;
212 
213 	trace_kvm_hv_synic_set_msr(vcpu->vcpu_id, msr, data, host);
214 
215 	ret = 0;
216 	switch (msr) {
217 	case HV_X64_MSR_SCONTROL:
218 		synic->control = data;
219 		if (!host)
220 			synic_exit(synic, msr);
221 		break;
222 	case HV_X64_MSR_SVERSION:
223 		if (!host) {
224 			ret = 1;
225 			break;
226 		}
227 		synic->version = data;
228 		break;
229 	case HV_X64_MSR_SIEFP:
230 		if ((data & HV_SYNIC_SIEFP_ENABLE) && !host &&
231 		    !synic->dont_zero_synic_pages)
232 			if (kvm_clear_guest(vcpu->kvm,
233 					    data & PAGE_MASK, PAGE_SIZE)) {
234 				ret = 1;
235 				break;
236 			}
237 		synic->evt_page = data;
238 		if (!host)
239 			synic_exit(synic, msr);
240 		break;
241 	case HV_X64_MSR_SIMP:
242 		if ((data & HV_SYNIC_SIMP_ENABLE) && !host &&
243 		    !synic->dont_zero_synic_pages)
244 			if (kvm_clear_guest(vcpu->kvm,
245 					    data & PAGE_MASK, PAGE_SIZE)) {
246 				ret = 1;
247 				break;
248 			}
249 		synic->msg_page = data;
250 		if (!host)
251 			synic_exit(synic, msr);
252 		break;
253 	case HV_X64_MSR_EOM: {
254 		int i;
255 
256 		for (i = 0; i < ARRAY_SIZE(synic->sint); i++)
257 			kvm_hv_notify_acked_sint(vcpu, i);
258 		break;
259 	}
260 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
261 		ret = synic_set_sint(synic, msr - HV_X64_MSR_SINT0, data, host);
262 		break;
263 	default:
264 		ret = 1;
265 		break;
266 	}
267 	return ret;
268 }
269 
270 static int synic_get_msr(struct kvm_vcpu_hv_synic *synic, u32 msr, u64 *pdata,
271 			 bool host)
272 {
273 	int ret;
274 
275 	if (!synic->active && !host)
276 		return 1;
277 
278 	ret = 0;
279 	switch (msr) {
280 	case HV_X64_MSR_SCONTROL:
281 		*pdata = synic->control;
282 		break;
283 	case HV_X64_MSR_SVERSION:
284 		*pdata = synic->version;
285 		break;
286 	case HV_X64_MSR_SIEFP:
287 		*pdata = synic->evt_page;
288 		break;
289 	case HV_X64_MSR_SIMP:
290 		*pdata = synic->msg_page;
291 		break;
292 	case HV_X64_MSR_EOM:
293 		*pdata = 0;
294 		break;
295 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
296 		*pdata = atomic64_read(&synic->sint[msr - HV_X64_MSR_SINT0]);
297 		break;
298 	default:
299 		ret = 1;
300 		break;
301 	}
302 	return ret;
303 }
304 
305 static int synic_set_irq(struct kvm_vcpu_hv_synic *synic, u32 sint)
306 {
307 	struct kvm_vcpu *vcpu = synic_to_vcpu(synic);
308 	struct kvm_lapic_irq irq;
309 	int ret, vector;
310 
311 	if (sint >= ARRAY_SIZE(synic->sint))
312 		return -EINVAL;
313 
314 	vector = synic_get_sint_vector(synic_read_sint(synic, sint));
315 	if (vector < 0)
316 		return -ENOENT;
317 
318 	memset(&irq, 0, sizeof(irq));
319 	irq.shorthand = APIC_DEST_SELF;
320 	irq.dest_mode = APIC_DEST_PHYSICAL;
321 	irq.delivery_mode = APIC_DM_FIXED;
322 	irq.vector = vector;
323 	irq.level = 1;
324 
325 	ret = kvm_irq_delivery_to_apic(vcpu->kvm, vcpu->arch.apic, &irq, NULL);
326 	trace_kvm_hv_synic_set_irq(vcpu->vcpu_id, sint, irq.vector, ret);
327 	return ret;
328 }
329 
330 int kvm_hv_synic_set_irq(struct kvm *kvm, u32 vpidx, u32 sint)
331 {
332 	struct kvm_vcpu_hv_synic *synic;
333 
334 	synic = synic_get(kvm, vpidx);
335 	if (!synic)
336 		return -EINVAL;
337 
338 	return synic_set_irq(synic, sint);
339 }
340 
341 void kvm_hv_synic_send_eoi(struct kvm_vcpu *vcpu, int vector)
342 {
343 	struct kvm_vcpu_hv_synic *synic = vcpu_to_synic(vcpu);
344 	int i;
345 
346 	trace_kvm_hv_synic_send_eoi(vcpu->vcpu_id, vector);
347 
348 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++)
349 		if (synic_get_sint_vector(synic_read_sint(synic, i)) == vector)
350 			kvm_hv_notify_acked_sint(vcpu, i);
351 }
352 
353 static int kvm_hv_set_sint_gsi(struct kvm *kvm, u32 vpidx, u32 sint, int gsi)
354 {
355 	struct kvm_vcpu_hv_synic *synic;
356 
357 	synic = synic_get(kvm, vpidx);
358 	if (!synic)
359 		return -EINVAL;
360 
361 	if (sint >= ARRAY_SIZE(synic->sint_to_gsi))
362 		return -EINVAL;
363 
364 	atomic_set(&synic->sint_to_gsi[sint], gsi);
365 	return 0;
366 }
367 
368 void kvm_hv_irq_routing_update(struct kvm *kvm)
369 {
370 	struct kvm_irq_routing_table *irq_rt;
371 	struct kvm_kernel_irq_routing_entry *e;
372 	u32 gsi;
373 
374 	irq_rt = srcu_dereference_check(kvm->irq_routing, &kvm->irq_srcu,
375 					lockdep_is_held(&kvm->irq_lock));
376 
377 	for (gsi = 0; gsi < irq_rt->nr_rt_entries; gsi++) {
378 		hlist_for_each_entry(e, &irq_rt->map[gsi], link) {
379 			if (e->type == KVM_IRQ_ROUTING_HV_SINT)
380 				kvm_hv_set_sint_gsi(kvm, e->hv_sint.vcpu,
381 						    e->hv_sint.sint, gsi);
382 		}
383 	}
384 }
385 
386 static void synic_init(struct kvm_vcpu_hv_synic *synic)
387 {
388 	int i;
389 
390 	memset(synic, 0, sizeof(*synic));
391 	synic->version = HV_SYNIC_VERSION_1;
392 	for (i = 0; i < ARRAY_SIZE(synic->sint); i++) {
393 		atomic64_set(&synic->sint[i], HV_SYNIC_SINT_MASKED);
394 		atomic_set(&synic->sint_to_gsi[i], -1);
395 	}
396 }
397 
398 static u64 get_time_ref_counter(struct kvm *kvm)
399 {
400 	struct kvm_hv *hv = &kvm->arch.hyperv;
401 	struct kvm_vcpu *vcpu;
402 	u64 tsc;
403 
404 	/*
405 	 * The guest has not set up the TSC page or the clock isn't
406 	 * stable, fall back to get_kvmclock_ns.
407 	 */
408 	if (!hv->tsc_ref.tsc_sequence)
409 		return div_u64(get_kvmclock_ns(kvm), 100);
410 
411 	vcpu = kvm_get_vcpu(kvm, 0);
412 	tsc = kvm_read_l1_tsc(vcpu, rdtsc());
413 	return mul_u64_u64_shr(tsc, hv->tsc_ref.tsc_scale, 64)
414 		+ hv->tsc_ref.tsc_offset;
415 }
416 
417 static void stimer_mark_pending(struct kvm_vcpu_hv_stimer *stimer,
418 				bool vcpu_kick)
419 {
420 	struct kvm_vcpu *vcpu = stimer_to_vcpu(stimer);
421 
422 	set_bit(stimer->index,
423 		vcpu_to_hv_vcpu(vcpu)->stimer_pending_bitmap);
424 	kvm_make_request(KVM_REQ_HV_STIMER, vcpu);
425 	if (vcpu_kick)
426 		kvm_vcpu_kick(vcpu);
427 }
428 
429 static void stimer_cleanup(struct kvm_vcpu_hv_stimer *stimer)
430 {
431 	struct kvm_vcpu *vcpu = stimer_to_vcpu(stimer);
432 
433 	trace_kvm_hv_stimer_cleanup(stimer_to_vcpu(stimer)->vcpu_id,
434 				    stimer->index);
435 
436 	hrtimer_cancel(&stimer->timer);
437 	clear_bit(stimer->index,
438 		  vcpu_to_hv_vcpu(vcpu)->stimer_pending_bitmap);
439 	stimer->msg_pending = false;
440 	stimer->exp_time = 0;
441 }
442 
443 static enum hrtimer_restart stimer_timer_callback(struct hrtimer *timer)
444 {
445 	struct kvm_vcpu_hv_stimer *stimer;
446 
447 	stimer = container_of(timer, struct kvm_vcpu_hv_stimer, timer);
448 	trace_kvm_hv_stimer_callback(stimer_to_vcpu(stimer)->vcpu_id,
449 				     stimer->index);
450 	stimer_mark_pending(stimer, true);
451 
452 	return HRTIMER_NORESTART;
453 }
454 
455 /*
456  * stimer_start() assumptions:
457  * a) stimer->count is not equal to 0
458  * b) stimer->config has HV_STIMER_ENABLE flag
459  */
460 static int stimer_start(struct kvm_vcpu_hv_stimer *stimer)
461 {
462 	u64 time_now;
463 	ktime_t ktime_now;
464 
465 	time_now = get_time_ref_counter(stimer_to_vcpu(stimer)->kvm);
466 	ktime_now = ktime_get();
467 
468 	if (stimer->config.periodic) {
469 		if (stimer->exp_time) {
470 			if (time_now >= stimer->exp_time) {
471 				u64 remainder;
472 
473 				div64_u64_rem(time_now - stimer->exp_time,
474 					      stimer->count, &remainder);
475 				stimer->exp_time =
476 					time_now + (stimer->count - remainder);
477 			}
478 		} else
479 			stimer->exp_time = time_now + stimer->count;
480 
481 		trace_kvm_hv_stimer_start_periodic(
482 					stimer_to_vcpu(stimer)->vcpu_id,
483 					stimer->index,
484 					time_now, stimer->exp_time);
485 
486 		hrtimer_start(&stimer->timer,
487 			      ktime_add_ns(ktime_now,
488 					   100 * (stimer->exp_time - time_now)),
489 			      HRTIMER_MODE_ABS);
490 		return 0;
491 	}
492 	stimer->exp_time = stimer->count;
493 	if (time_now >= stimer->count) {
494 		/*
495 		 * Expire timer according to Hypervisor Top-Level Functional
496 		 * specification v4(15.3.1):
497 		 * "If a one shot is enabled and the specified count is in
498 		 * the past, it will expire immediately."
499 		 */
500 		stimer_mark_pending(stimer, false);
501 		return 0;
502 	}
503 
504 	trace_kvm_hv_stimer_start_one_shot(stimer_to_vcpu(stimer)->vcpu_id,
505 					   stimer->index,
506 					   time_now, stimer->count);
507 
508 	hrtimer_start(&stimer->timer,
509 		      ktime_add_ns(ktime_now, 100 * (stimer->count - time_now)),
510 		      HRTIMER_MODE_ABS);
511 	return 0;
512 }
513 
514 static int stimer_set_config(struct kvm_vcpu_hv_stimer *stimer, u64 config,
515 			     bool host)
516 {
517 	union hv_stimer_config new_config = {.as_uint64 = config},
518 		old_config = {.as_uint64 = stimer->config.as_uint64};
519 
520 	trace_kvm_hv_stimer_set_config(stimer_to_vcpu(stimer)->vcpu_id,
521 				       stimer->index, config, host);
522 
523 	stimer_cleanup(stimer);
524 	if (old_config.enable &&
525 	    !new_config.direct_mode && new_config.sintx == 0)
526 		new_config.enable = 0;
527 	stimer->config.as_uint64 = new_config.as_uint64;
528 
529 	if (stimer->config.enable)
530 		stimer_mark_pending(stimer, false);
531 
532 	return 0;
533 }
534 
535 static int stimer_set_count(struct kvm_vcpu_hv_stimer *stimer, u64 count,
536 			    bool host)
537 {
538 	trace_kvm_hv_stimer_set_count(stimer_to_vcpu(stimer)->vcpu_id,
539 				      stimer->index, count, host);
540 
541 	stimer_cleanup(stimer);
542 	stimer->count = count;
543 	if (stimer->count == 0)
544 		stimer->config.enable = 0;
545 	else if (stimer->config.auto_enable)
546 		stimer->config.enable = 1;
547 
548 	if (stimer->config.enable)
549 		stimer_mark_pending(stimer, false);
550 
551 	return 0;
552 }
553 
554 static int stimer_get_config(struct kvm_vcpu_hv_stimer *stimer, u64 *pconfig)
555 {
556 	*pconfig = stimer->config.as_uint64;
557 	return 0;
558 }
559 
560 static int stimer_get_count(struct kvm_vcpu_hv_stimer *stimer, u64 *pcount)
561 {
562 	*pcount = stimer->count;
563 	return 0;
564 }
565 
566 static int synic_deliver_msg(struct kvm_vcpu_hv_synic *synic, u32 sint,
567 			     struct hv_message *src_msg, bool no_retry)
568 {
569 	struct kvm_vcpu *vcpu = synic_to_vcpu(synic);
570 	int msg_off = offsetof(struct hv_message_page, sint_message[sint]);
571 	gfn_t msg_page_gfn;
572 	struct hv_message_header hv_hdr;
573 	int r;
574 
575 	if (!(synic->msg_page & HV_SYNIC_SIMP_ENABLE))
576 		return -ENOENT;
577 
578 	msg_page_gfn = synic->msg_page >> PAGE_SHIFT;
579 
580 	/*
581 	 * Strictly following the spec-mandated ordering would assume setting
582 	 * .msg_pending before checking .message_type.  However, this function
583 	 * is only called in vcpu context so the entire update is atomic from
584 	 * guest POV and thus the exact order here doesn't matter.
585 	 */
586 	r = kvm_vcpu_read_guest_page(vcpu, msg_page_gfn, &hv_hdr.message_type,
587 				     msg_off + offsetof(struct hv_message,
588 							header.message_type),
589 				     sizeof(hv_hdr.message_type));
590 	if (r < 0)
591 		return r;
592 
593 	if (hv_hdr.message_type != HVMSG_NONE) {
594 		if (no_retry)
595 			return 0;
596 
597 		hv_hdr.message_flags.msg_pending = 1;
598 		r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn,
599 					      &hv_hdr.message_flags,
600 					      msg_off +
601 					      offsetof(struct hv_message,
602 						       header.message_flags),
603 					      sizeof(hv_hdr.message_flags));
604 		if (r < 0)
605 			return r;
606 		return -EAGAIN;
607 	}
608 
609 	r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn, src_msg, msg_off,
610 				      sizeof(src_msg->header) +
611 				      src_msg->header.payload_size);
612 	if (r < 0)
613 		return r;
614 
615 	r = synic_set_irq(synic, sint);
616 	if (r < 0)
617 		return r;
618 	if (r == 0)
619 		return -EFAULT;
620 	return 0;
621 }
622 
623 static int stimer_send_msg(struct kvm_vcpu_hv_stimer *stimer)
624 {
625 	struct kvm_vcpu *vcpu = stimer_to_vcpu(stimer);
626 	struct hv_message *msg = &stimer->msg;
627 	struct hv_timer_message_payload *payload =
628 			(struct hv_timer_message_payload *)&msg->u.payload;
629 
630 	/*
631 	 * To avoid piling up periodic ticks, don't retry message
632 	 * delivery for them (within "lazy" lost ticks policy).
633 	 */
634 	bool no_retry = stimer->config.periodic;
635 
636 	payload->expiration_time = stimer->exp_time;
637 	payload->delivery_time = get_time_ref_counter(vcpu->kvm);
638 	return synic_deliver_msg(vcpu_to_synic(vcpu),
639 				 stimer->config.sintx, msg,
640 				 no_retry);
641 }
642 
643 static int stimer_notify_direct(struct kvm_vcpu_hv_stimer *stimer)
644 {
645 	struct kvm_vcpu *vcpu = stimer_to_vcpu(stimer);
646 	struct kvm_lapic_irq irq = {
647 		.delivery_mode = APIC_DM_FIXED,
648 		.vector = stimer->config.apic_vector
649 	};
650 
651 	return !kvm_apic_set_irq(vcpu, &irq, NULL);
652 }
653 
654 static void stimer_expiration(struct kvm_vcpu_hv_stimer *stimer)
655 {
656 	int r, direct = stimer->config.direct_mode;
657 
658 	stimer->msg_pending = true;
659 	if (!direct)
660 		r = stimer_send_msg(stimer);
661 	else
662 		r = stimer_notify_direct(stimer);
663 	trace_kvm_hv_stimer_expiration(stimer_to_vcpu(stimer)->vcpu_id,
664 				       stimer->index, direct, r);
665 	if (!r) {
666 		stimer->msg_pending = false;
667 		if (!(stimer->config.periodic))
668 			stimer->config.enable = 0;
669 	}
670 }
671 
672 void kvm_hv_process_stimers(struct kvm_vcpu *vcpu)
673 {
674 	struct kvm_vcpu_hv *hv_vcpu = vcpu_to_hv_vcpu(vcpu);
675 	struct kvm_vcpu_hv_stimer *stimer;
676 	u64 time_now, exp_time;
677 	int i;
678 
679 	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
680 		if (test_and_clear_bit(i, hv_vcpu->stimer_pending_bitmap)) {
681 			stimer = &hv_vcpu->stimer[i];
682 			if (stimer->config.enable) {
683 				exp_time = stimer->exp_time;
684 
685 				if (exp_time) {
686 					time_now =
687 						get_time_ref_counter(vcpu->kvm);
688 					if (time_now >= exp_time)
689 						stimer_expiration(stimer);
690 				}
691 
692 				if ((stimer->config.enable) &&
693 				    stimer->count) {
694 					if (!stimer->msg_pending)
695 						stimer_start(stimer);
696 				} else
697 					stimer_cleanup(stimer);
698 			}
699 		}
700 }
701 
702 void kvm_hv_vcpu_uninit(struct kvm_vcpu *vcpu)
703 {
704 	struct kvm_vcpu_hv *hv_vcpu = vcpu_to_hv_vcpu(vcpu);
705 	int i;
706 
707 	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
708 		stimer_cleanup(&hv_vcpu->stimer[i]);
709 }
710 
711 bool kvm_hv_assist_page_enabled(struct kvm_vcpu *vcpu)
712 {
713 	if (!(vcpu->arch.hyperv.hv_vapic & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE))
714 		return false;
715 	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
716 }
717 EXPORT_SYMBOL_GPL(kvm_hv_assist_page_enabled);
718 
719 bool kvm_hv_get_assist_page(struct kvm_vcpu *vcpu,
720 			    struct hv_vp_assist_page *assist_page)
721 {
722 	if (!kvm_hv_assist_page_enabled(vcpu))
723 		return false;
724 	return !kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data,
725 				      assist_page, sizeof(*assist_page));
726 }
727 EXPORT_SYMBOL_GPL(kvm_hv_get_assist_page);
728 
729 static void stimer_prepare_msg(struct kvm_vcpu_hv_stimer *stimer)
730 {
731 	struct hv_message *msg = &stimer->msg;
732 	struct hv_timer_message_payload *payload =
733 			(struct hv_timer_message_payload *)&msg->u.payload;
734 
735 	memset(&msg->header, 0, sizeof(msg->header));
736 	msg->header.message_type = HVMSG_TIMER_EXPIRED;
737 	msg->header.payload_size = sizeof(*payload);
738 
739 	payload->timer_index = stimer->index;
740 	payload->expiration_time = 0;
741 	payload->delivery_time = 0;
742 }
743 
744 static void stimer_init(struct kvm_vcpu_hv_stimer *stimer, int timer_index)
745 {
746 	memset(stimer, 0, sizeof(*stimer));
747 	stimer->index = timer_index;
748 	hrtimer_init(&stimer->timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
749 	stimer->timer.function = stimer_timer_callback;
750 	stimer_prepare_msg(stimer);
751 }
752 
753 void kvm_hv_vcpu_init(struct kvm_vcpu *vcpu)
754 {
755 	struct kvm_vcpu_hv *hv_vcpu = vcpu_to_hv_vcpu(vcpu);
756 	int i;
757 
758 	synic_init(&hv_vcpu->synic);
759 
760 	bitmap_zero(hv_vcpu->stimer_pending_bitmap, HV_SYNIC_STIMER_COUNT);
761 	for (i = 0; i < ARRAY_SIZE(hv_vcpu->stimer); i++)
762 		stimer_init(&hv_vcpu->stimer[i], i);
763 }
764 
765 void kvm_hv_vcpu_postcreate(struct kvm_vcpu *vcpu)
766 {
767 	struct kvm_vcpu_hv *hv_vcpu = vcpu_to_hv_vcpu(vcpu);
768 
769 	hv_vcpu->vp_index = kvm_vcpu_get_idx(vcpu);
770 }
771 
772 int kvm_hv_activate_synic(struct kvm_vcpu *vcpu, bool dont_zero_synic_pages)
773 {
774 	struct kvm_vcpu_hv_synic *synic = vcpu_to_synic(vcpu);
775 
776 	/*
777 	 * Hyper-V SynIC auto EOI SINT's are
778 	 * not compatible with APICV, so deactivate APICV
779 	 */
780 	kvm_vcpu_deactivate_apicv(vcpu);
781 	synic->active = true;
782 	synic->dont_zero_synic_pages = dont_zero_synic_pages;
783 	return 0;
784 }
785 
786 static bool kvm_hv_msr_partition_wide(u32 msr)
787 {
788 	bool r = false;
789 
790 	switch (msr) {
791 	case HV_X64_MSR_GUEST_OS_ID:
792 	case HV_X64_MSR_HYPERCALL:
793 	case HV_X64_MSR_REFERENCE_TSC:
794 	case HV_X64_MSR_TIME_REF_COUNT:
795 	case HV_X64_MSR_CRASH_CTL:
796 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
797 	case HV_X64_MSR_RESET:
798 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
799 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
800 	case HV_X64_MSR_TSC_EMULATION_STATUS:
801 		r = true;
802 		break;
803 	}
804 
805 	return r;
806 }
807 
808 static int kvm_hv_msr_get_crash_data(struct kvm_vcpu *vcpu,
809 				     u32 index, u64 *pdata)
810 {
811 	struct kvm_hv *hv = &vcpu->kvm->arch.hyperv;
812 
813 	if (WARN_ON_ONCE(index >= ARRAY_SIZE(hv->hv_crash_param)))
814 		return -EINVAL;
815 
816 	*pdata = hv->hv_crash_param[index];
817 	return 0;
818 }
819 
820 static int kvm_hv_msr_get_crash_ctl(struct kvm_vcpu *vcpu, u64 *pdata)
821 {
822 	struct kvm_hv *hv = &vcpu->kvm->arch.hyperv;
823 
824 	*pdata = hv->hv_crash_ctl;
825 	return 0;
826 }
827 
828 static int kvm_hv_msr_set_crash_ctl(struct kvm_vcpu *vcpu, u64 data, bool host)
829 {
830 	struct kvm_hv *hv = &vcpu->kvm->arch.hyperv;
831 
832 	if (host)
833 		hv->hv_crash_ctl = data & HV_CRASH_CTL_CRASH_NOTIFY;
834 
835 	if (!host && (data & HV_CRASH_CTL_CRASH_NOTIFY)) {
836 
837 		vcpu_debug(vcpu, "hv crash (0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n",
838 			  hv->hv_crash_param[0],
839 			  hv->hv_crash_param[1],
840 			  hv->hv_crash_param[2],
841 			  hv->hv_crash_param[3],
842 			  hv->hv_crash_param[4]);
843 
844 		/* Send notification about crash to user space */
845 		kvm_make_request(KVM_REQ_HV_CRASH, vcpu);
846 	}
847 
848 	return 0;
849 }
850 
851 static int kvm_hv_msr_set_crash_data(struct kvm_vcpu *vcpu,
852 				     u32 index, u64 data)
853 {
854 	struct kvm_hv *hv = &vcpu->kvm->arch.hyperv;
855 
856 	if (WARN_ON_ONCE(index >= ARRAY_SIZE(hv->hv_crash_param)))
857 		return -EINVAL;
858 
859 	hv->hv_crash_param[index] = data;
860 	return 0;
861 }
862 
863 /*
864  * The kvmclock and Hyper-V TSC page use similar formulas, and converting
865  * between them is possible:
866  *
867  * kvmclock formula:
868  *    nsec = (ticks - tsc_timestamp) * tsc_to_system_mul * 2^(tsc_shift-32)
869  *           + system_time
870  *
871  * Hyper-V formula:
872  *    nsec/100 = ticks * scale / 2^64 + offset
873  *
874  * When tsc_timestamp = system_time = 0, offset is zero in the Hyper-V formula.
875  * By dividing the kvmclock formula by 100 and equating what's left we get:
876  *    ticks * scale / 2^64 = ticks * tsc_to_system_mul * 2^(tsc_shift-32) / 100
877  *            scale / 2^64 =         tsc_to_system_mul * 2^(tsc_shift-32) / 100
878  *            scale        =         tsc_to_system_mul * 2^(32+tsc_shift) / 100
879  *
880  * Now expand the kvmclock formula and divide by 100:
881  *    nsec = ticks * tsc_to_system_mul * 2^(tsc_shift-32)
882  *           - tsc_timestamp * tsc_to_system_mul * 2^(tsc_shift-32)
883  *           + system_time
884  *    nsec/100 = ticks * tsc_to_system_mul * 2^(tsc_shift-32) / 100
885  *               - tsc_timestamp * tsc_to_system_mul * 2^(tsc_shift-32) / 100
886  *               + system_time / 100
887  *
888  * Replace tsc_to_system_mul * 2^(tsc_shift-32) / 100 by scale / 2^64:
889  *    nsec/100 = ticks * scale / 2^64
890  *               - tsc_timestamp * scale / 2^64
891  *               + system_time / 100
892  *
893  * Equate with the Hyper-V formula so that ticks * scale / 2^64 cancels out:
894  *    offset = system_time / 100 - tsc_timestamp * scale / 2^64
895  *
896  * These two equivalencies are implemented in this function.
897  */
898 static bool compute_tsc_page_parameters(struct pvclock_vcpu_time_info *hv_clock,
899 					HV_REFERENCE_TSC_PAGE *tsc_ref)
900 {
901 	u64 max_mul;
902 
903 	if (!(hv_clock->flags & PVCLOCK_TSC_STABLE_BIT))
904 		return false;
905 
906 	/*
907 	 * check if scale would overflow, if so we use the time ref counter
908 	 *    tsc_to_system_mul * 2^(tsc_shift+32) / 100 >= 2^64
909 	 *    tsc_to_system_mul / 100 >= 2^(32-tsc_shift)
910 	 *    tsc_to_system_mul >= 100 * 2^(32-tsc_shift)
911 	 */
912 	max_mul = 100ull << (32 - hv_clock->tsc_shift);
913 	if (hv_clock->tsc_to_system_mul >= max_mul)
914 		return false;
915 
916 	/*
917 	 * Otherwise compute the scale and offset according to the formulas
918 	 * derived above.
919 	 */
920 	tsc_ref->tsc_scale =
921 		mul_u64_u32_div(1ULL << (32 + hv_clock->tsc_shift),
922 				hv_clock->tsc_to_system_mul,
923 				100);
924 
925 	tsc_ref->tsc_offset = hv_clock->system_time;
926 	do_div(tsc_ref->tsc_offset, 100);
927 	tsc_ref->tsc_offset -=
928 		mul_u64_u64_shr(hv_clock->tsc_timestamp, tsc_ref->tsc_scale, 64);
929 	return true;
930 }
931 
932 void kvm_hv_setup_tsc_page(struct kvm *kvm,
933 			   struct pvclock_vcpu_time_info *hv_clock)
934 {
935 	struct kvm_hv *hv = &kvm->arch.hyperv;
936 	u32 tsc_seq;
937 	u64 gfn;
938 
939 	BUILD_BUG_ON(sizeof(tsc_seq) != sizeof(hv->tsc_ref.tsc_sequence));
940 	BUILD_BUG_ON(offsetof(HV_REFERENCE_TSC_PAGE, tsc_sequence) != 0);
941 
942 	if (!(hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE))
943 		return;
944 
945 	mutex_lock(&kvm->arch.hyperv.hv_lock);
946 	if (!(hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE))
947 		goto out_unlock;
948 
949 	gfn = hv->hv_tsc_page >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT;
950 	/*
951 	 * Because the TSC parameters only vary when there is a
952 	 * change in the master clock, do not bother with caching.
953 	 */
954 	if (unlikely(kvm_read_guest(kvm, gfn_to_gpa(gfn),
955 				    &tsc_seq, sizeof(tsc_seq))))
956 		goto out_unlock;
957 
958 	/*
959 	 * While we're computing and writing the parameters, force the
960 	 * guest to use the time reference count MSR.
961 	 */
962 	hv->tsc_ref.tsc_sequence = 0;
963 	if (kvm_write_guest(kvm, gfn_to_gpa(gfn),
964 			    &hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence)))
965 		goto out_unlock;
966 
967 	if (!compute_tsc_page_parameters(hv_clock, &hv->tsc_ref))
968 		goto out_unlock;
969 
970 	/* Ensure sequence is zero before writing the rest of the struct.  */
971 	smp_wmb();
972 	if (kvm_write_guest(kvm, gfn_to_gpa(gfn), &hv->tsc_ref, sizeof(hv->tsc_ref)))
973 		goto out_unlock;
974 
975 	/*
976 	 * Now switch to the TSC page mechanism by writing the sequence.
977 	 */
978 	tsc_seq++;
979 	if (tsc_seq == 0xFFFFFFFF || tsc_seq == 0)
980 		tsc_seq = 1;
981 
982 	/* Write the struct entirely before the non-zero sequence.  */
983 	smp_wmb();
984 
985 	hv->tsc_ref.tsc_sequence = tsc_seq;
986 	kvm_write_guest(kvm, gfn_to_gpa(gfn),
987 			&hv->tsc_ref, sizeof(hv->tsc_ref.tsc_sequence));
988 out_unlock:
989 	mutex_unlock(&kvm->arch.hyperv.hv_lock);
990 }
991 
992 static int kvm_hv_set_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data,
993 			     bool host)
994 {
995 	struct kvm *kvm = vcpu->kvm;
996 	struct kvm_hv *hv = &kvm->arch.hyperv;
997 
998 	switch (msr) {
999 	case HV_X64_MSR_GUEST_OS_ID:
1000 		hv->hv_guest_os_id = data;
1001 		/* setting guest os id to zero disables hypercall page */
1002 		if (!hv->hv_guest_os_id)
1003 			hv->hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
1004 		break;
1005 	case HV_X64_MSR_HYPERCALL: {
1006 		u64 gfn;
1007 		unsigned long addr;
1008 		u8 instructions[4];
1009 
1010 		/* if guest os id is not set hypercall should remain disabled */
1011 		if (!hv->hv_guest_os_id)
1012 			break;
1013 		if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
1014 			hv->hv_hypercall = data;
1015 			break;
1016 		}
1017 		gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
1018 		addr = gfn_to_hva(kvm, gfn);
1019 		if (kvm_is_error_hva(addr))
1020 			return 1;
1021 		kvm_x86_ops->patch_hypercall(vcpu, instructions);
1022 		((unsigned char *)instructions)[3] = 0xc3; /* ret */
1023 		if (__copy_to_user((void __user *)addr, instructions, 4))
1024 			return 1;
1025 		hv->hv_hypercall = data;
1026 		mark_page_dirty(kvm, gfn);
1027 		break;
1028 	}
1029 	case HV_X64_MSR_REFERENCE_TSC:
1030 		hv->hv_tsc_page = data;
1031 		if (hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE)
1032 			kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
1033 		break;
1034 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1035 		return kvm_hv_msr_set_crash_data(vcpu,
1036 						 msr - HV_X64_MSR_CRASH_P0,
1037 						 data);
1038 	case HV_X64_MSR_CRASH_CTL:
1039 		return kvm_hv_msr_set_crash_ctl(vcpu, data, host);
1040 	case HV_X64_MSR_RESET:
1041 		if (data == 1) {
1042 			vcpu_debug(vcpu, "hyper-v reset requested\n");
1043 			kvm_make_request(KVM_REQ_HV_RESET, vcpu);
1044 		}
1045 		break;
1046 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1047 		hv->hv_reenlightenment_control = data;
1048 		break;
1049 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
1050 		hv->hv_tsc_emulation_control = data;
1051 		break;
1052 	case HV_X64_MSR_TSC_EMULATION_STATUS:
1053 		hv->hv_tsc_emulation_status = data;
1054 		break;
1055 	case HV_X64_MSR_TIME_REF_COUNT:
1056 		/* read-only, but still ignore it if host-initiated */
1057 		if (!host)
1058 			return 1;
1059 		break;
1060 	default:
1061 		vcpu_unimpl(vcpu, "Hyper-V uhandled wrmsr: 0x%x data 0x%llx\n",
1062 			    msr, data);
1063 		return 1;
1064 	}
1065 	return 0;
1066 }
1067 
1068 /* Calculate cpu time spent by current task in 100ns units */
1069 static u64 current_task_runtime_100ns(void)
1070 {
1071 	u64 utime, stime;
1072 
1073 	task_cputime_adjusted(current, &utime, &stime);
1074 
1075 	return div_u64(utime + stime, 100);
1076 }
1077 
1078 static int kvm_hv_set_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1079 {
1080 	struct kvm_vcpu_hv *hv_vcpu = &vcpu->arch.hyperv;
1081 
1082 	switch (msr) {
1083 	case HV_X64_MSR_VP_INDEX: {
1084 		struct kvm_hv *hv = &vcpu->kvm->arch.hyperv;
1085 		int vcpu_idx = kvm_vcpu_get_idx(vcpu);
1086 		u32 new_vp_index = (u32)data;
1087 
1088 		if (!host || new_vp_index >= KVM_MAX_VCPUS)
1089 			return 1;
1090 
1091 		if (new_vp_index == hv_vcpu->vp_index)
1092 			return 0;
1093 
1094 		/*
1095 		 * The VP index is initialized to vcpu_index by
1096 		 * kvm_hv_vcpu_postcreate so they initially match.  Now the
1097 		 * VP index is changing, adjust num_mismatched_vp_indexes if
1098 		 * it now matches or no longer matches vcpu_idx.
1099 		 */
1100 		if (hv_vcpu->vp_index == vcpu_idx)
1101 			atomic_inc(&hv->num_mismatched_vp_indexes);
1102 		else if (new_vp_index == vcpu_idx)
1103 			atomic_dec(&hv->num_mismatched_vp_indexes);
1104 
1105 		hv_vcpu->vp_index = new_vp_index;
1106 		break;
1107 	}
1108 	case HV_X64_MSR_VP_ASSIST_PAGE: {
1109 		u64 gfn;
1110 		unsigned long addr;
1111 
1112 		if (!(data & HV_X64_MSR_VP_ASSIST_PAGE_ENABLE)) {
1113 			hv_vcpu->hv_vapic = data;
1114 			if (kvm_lapic_enable_pv_eoi(vcpu, 0, 0))
1115 				return 1;
1116 			break;
1117 		}
1118 		gfn = data >> HV_X64_MSR_VP_ASSIST_PAGE_ADDRESS_SHIFT;
1119 		addr = kvm_vcpu_gfn_to_hva(vcpu, gfn);
1120 		if (kvm_is_error_hva(addr))
1121 			return 1;
1122 
1123 		/*
1124 		 * Clear apic_assist portion of f(struct hv_vp_assist_page
1125 		 * only, there can be valuable data in the rest which needs
1126 		 * to be preserved e.g. on migration.
1127 		 */
1128 		if (__clear_user((void __user *)addr, sizeof(u32)))
1129 			return 1;
1130 		hv_vcpu->hv_vapic = data;
1131 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
1132 		if (kvm_lapic_enable_pv_eoi(vcpu,
1133 					    gfn_to_gpa(gfn) | KVM_MSR_ENABLED,
1134 					    sizeof(struct hv_vp_assist_page)))
1135 			return 1;
1136 		break;
1137 	}
1138 	case HV_X64_MSR_EOI:
1139 		return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
1140 	case HV_X64_MSR_ICR:
1141 		return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
1142 	case HV_X64_MSR_TPR:
1143 		return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
1144 	case HV_X64_MSR_VP_RUNTIME:
1145 		if (!host)
1146 			return 1;
1147 		hv_vcpu->runtime_offset = data - current_task_runtime_100ns();
1148 		break;
1149 	case HV_X64_MSR_SCONTROL:
1150 	case HV_X64_MSR_SVERSION:
1151 	case HV_X64_MSR_SIEFP:
1152 	case HV_X64_MSR_SIMP:
1153 	case HV_X64_MSR_EOM:
1154 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1155 		return synic_set_msr(vcpu_to_synic(vcpu), msr, data, host);
1156 	case HV_X64_MSR_STIMER0_CONFIG:
1157 	case HV_X64_MSR_STIMER1_CONFIG:
1158 	case HV_X64_MSR_STIMER2_CONFIG:
1159 	case HV_X64_MSR_STIMER3_CONFIG: {
1160 		int timer_index = (msr - HV_X64_MSR_STIMER0_CONFIG)/2;
1161 
1162 		return stimer_set_config(vcpu_to_stimer(vcpu, timer_index),
1163 					 data, host);
1164 	}
1165 	case HV_X64_MSR_STIMER0_COUNT:
1166 	case HV_X64_MSR_STIMER1_COUNT:
1167 	case HV_X64_MSR_STIMER2_COUNT:
1168 	case HV_X64_MSR_STIMER3_COUNT: {
1169 		int timer_index = (msr - HV_X64_MSR_STIMER0_COUNT)/2;
1170 
1171 		return stimer_set_count(vcpu_to_stimer(vcpu, timer_index),
1172 					data, host);
1173 	}
1174 	case HV_X64_MSR_TSC_FREQUENCY:
1175 	case HV_X64_MSR_APIC_FREQUENCY:
1176 		/* read-only, but still ignore it if host-initiated */
1177 		if (!host)
1178 			return 1;
1179 		break;
1180 	default:
1181 		vcpu_unimpl(vcpu, "Hyper-V uhandled wrmsr: 0x%x data 0x%llx\n",
1182 			    msr, data);
1183 		return 1;
1184 	}
1185 
1186 	return 0;
1187 }
1188 
1189 static int kvm_hv_get_msr_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
1190 {
1191 	u64 data = 0;
1192 	struct kvm *kvm = vcpu->kvm;
1193 	struct kvm_hv *hv = &kvm->arch.hyperv;
1194 
1195 	switch (msr) {
1196 	case HV_X64_MSR_GUEST_OS_ID:
1197 		data = hv->hv_guest_os_id;
1198 		break;
1199 	case HV_X64_MSR_HYPERCALL:
1200 		data = hv->hv_hypercall;
1201 		break;
1202 	case HV_X64_MSR_TIME_REF_COUNT:
1203 		data = get_time_ref_counter(kvm);
1204 		break;
1205 	case HV_X64_MSR_REFERENCE_TSC:
1206 		data = hv->hv_tsc_page;
1207 		break;
1208 	case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:
1209 		return kvm_hv_msr_get_crash_data(vcpu,
1210 						 msr - HV_X64_MSR_CRASH_P0,
1211 						 pdata);
1212 	case HV_X64_MSR_CRASH_CTL:
1213 		return kvm_hv_msr_get_crash_ctl(vcpu, pdata);
1214 	case HV_X64_MSR_RESET:
1215 		data = 0;
1216 		break;
1217 	case HV_X64_MSR_REENLIGHTENMENT_CONTROL:
1218 		data = hv->hv_reenlightenment_control;
1219 		break;
1220 	case HV_X64_MSR_TSC_EMULATION_CONTROL:
1221 		data = hv->hv_tsc_emulation_control;
1222 		break;
1223 	case HV_X64_MSR_TSC_EMULATION_STATUS:
1224 		data = hv->hv_tsc_emulation_status;
1225 		break;
1226 	default:
1227 		vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1228 		return 1;
1229 	}
1230 
1231 	*pdata = data;
1232 	return 0;
1233 }
1234 
1235 static int kvm_hv_get_msr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata,
1236 			  bool host)
1237 {
1238 	u64 data = 0;
1239 	struct kvm_vcpu_hv *hv_vcpu = &vcpu->arch.hyperv;
1240 
1241 	switch (msr) {
1242 	case HV_X64_MSR_VP_INDEX:
1243 		data = hv_vcpu->vp_index;
1244 		break;
1245 	case HV_X64_MSR_EOI:
1246 		return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
1247 	case HV_X64_MSR_ICR:
1248 		return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
1249 	case HV_X64_MSR_TPR:
1250 		return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
1251 	case HV_X64_MSR_VP_ASSIST_PAGE:
1252 		data = hv_vcpu->hv_vapic;
1253 		break;
1254 	case HV_X64_MSR_VP_RUNTIME:
1255 		data = current_task_runtime_100ns() + hv_vcpu->runtime_offset;
1256 		break;
1257 	case HV_X64_MSR_SCONTROL:
1258 	case HV_X64_MSR_SVERSION:
1259 	case HV_X64_MSR_SIEFP:
1260 	case HV_X64_MSR_SIMP:
1261 	case HV_X64_MSR_EOM:
1262 	case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:
1263 		return synic_get_msr(vcpu_to_synic(vcpu), msr, pdata, host);
1264 	case HV_X64_MSR_STIMER0_CONFIG:
1265 	case HV_X64_MSR_STIMER1_CONFIG:
1266 	case HV_X64_MSR_STIMER2_CONFIG:
1267 	case HV_X64_MSR_STIMER3_CONFIG: {
1268 		int timer_index = (msr - HV_X64_MSR_STIMER0_CONFIG)/2;
1269 
1270 		return stimer_get_config(vcpu_to_stimer(vcpu, timer_index),
1271 					 pdata);
1272 	}
1273 	case HV_X64_MSR_STIMER0_COUNT:
1274 	case HV_X64_MSR_STIMER1_COUNT:
1275 	case HV_X64_MSR_STIMER2_COUNT:
1276 	case HV_X64_MSR_STIMER3_COUNT: {
1277 		int timer_index = (msr - HV_X64_MSR_STIMER0_COUNT)/2;
1278 
1279 		return stimer_get_count(vcpu_to_stimer(vcpu, timer_index),
1280 					pdata);
1281 	}
1282 	case HV_X64_MSR_TSC_FREQUENCY:
1283 		data = (u64)vcpu->arch.virtual_tsc_khz * 1000;
1284 		break;
1285 	case HV_X64_MSR_APIC_FREQUENCY:
1286 		data = APIC_BUS_FREQUENCY;
1287 		break;
1288 	default:
1289 		vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
1290 		return 1;
1291 	}
1292 	*pdata = data;
1293 	return 0;
1294 }
1295 
1296 int kvm_hv_set_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 data, bool host)
1297 {
1298 	if (kvm_hv_msr_partition_wide(msr)) {
1299 		int r;
1300 
1301 		mutex_lock(&vcpu->kvm->arch.hyperv.hv_lock);
1302 		r = kvm_hv_set_msr_pw(vcpu, msr, data, host);
1303 		mutex_unlock(&vcpu->kvm->arch.hyperv.hv_lock);
1304 		return r;
1305 	} else
1306 		return kvm_hv_set_msr(vcpu, msr, data, host);
1307 }
1308 
1309 int kvm_hv_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata, bool host)
1310 {
1311 	if (kvm_hv_msr_partition_wide(msr)) {
1312 		int r;
1313 
1314 		mutex_lock(&vcpu->kvm->arch.hyperv.hv_lock);
1315 		r = kvm_hv_get_msr_pw(vcpu, msr, pdata);
1316 		mutex_unlock(&vcpu->kvm->arch.hyperv.hv_lock);
1317 		return r;
1318 	} else
1319 		return kvm_hv_get_msr(vcpu, msr, pdata, host);
1320 }
1321 
1322 static __always_inline unsigned long *sparse_set_to_vcpu_mask(
1323 	struct kvm *kvm, u64 *sparse_banks, u64 valid_bank_mask,
1324 	u64 *vp_bitmap, unsigned long *vcpu_bitmap)
1325 {
1326 	struct kvm_hv *hv = &kvm->arch.hyperv;
1327 	struct kvm_vcpu *vcpu;
1328 	int i, bank, sbank = 0;
1329 
1330 	memset(vp_bitmap, 0,
1331 	       KVM_HV_MAX_SPARSE_VCPU_SET_BITS * sizeof(*vp_bitmap));
1332 	for_each_set_bit(bank, (unsigned long *)&valid_bank_mask,
1333 			 KVM_HV_MAX_SPARSE_VCPU_SET_BITS)
1334 		vp_bitmap[bank] = sparse_banks[sbank++];
1335 
1336 	if (likely(!atomic_read(&hv->num_mismatched_vp_indexes))) {
1337 		/* for all vcpus vp_index == vcpu_idx */
1338 		return (unsigned long *)vp_bitmap;
1339 	}
1340 
1341 	bitmap_zero(vcpu_bitmap, KVM_MAX_VCPUS);
1342 	kvm_for_each_vcpu(i, vcpu, kvm) {
1343 		if (test_bit(vcpu_to_hv_vcpu(vcpu)->vp_index,
1344 			     (unsigned long *)vp_bitmap))
1345 			__set_bit(i, vcpu_bitmap);
1346 	}
1347 	return vcpu_bitmap;
1348 }
1349 
1350 static u64 kvm_hv_flush_tlb(struct kvm_vcpu *current_vcpu, u64 ingpa,
1351 			    u16 rep_cnt, bool ex)
1352 {
1353 	struct kvm *kvm = current_vcpu->kvm;
1354 	struct kvm_vcpu_hv *hv_vcpu = &current_vcpu->arch.hyperv;
1355 	struct hv_tlb_flush_ex flush_ex;
1356 	struct hv_tlb_flush flush;
1357 	u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
1358 	DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
1359 	unsigned long *vcpu_mask;
1360 	u64 valid_bank_mask;
1361 	u64 sparse_banks[64];
1362 	int sparse_banks_len;
1363 	bool all_cpus;
1364 
1365 	if (!ex) {
1366 		if (unlikely(kvm_read_guest(kvm, ingpa, &flush, sizeof(flush))))
1367 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
1368 
1369 		trace_kvm_hv_flush_tlb(flush.processor_mask,
1370 				       flush.address_space, flush.flags);
1371 
1372 		valid_bank_mask = BIT_ULL(0);
1373 		sparse_banks[0] = flush.processor_mask;
1374 		all_cpus = flush.flags & HV_FLUSH_ALL_PROCESSORS;
1375 	} else {
1376 		if (unlikely(kvm_read_guest(kvm, ingpa, &flush_ex,
1377 					    sizeof(flush_ex))))
1378 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
1379 
1380 		trace_kvm_hv_flush_tlb_ex(flush_ex.hv_vp_set.valid_bank_mask,
1381 					  flush_ex.hv_vp_set.format,
1382 					  flush_ex.address_space,
1383 					  flush_ex.flags);
1384 
1385 		valid_bank_mask = flush_ex.hv_vp_set.valid_bank_mask;
1386 		all_cpus = flush_ex.hv_vp_set.format !=
1387 			HV_GENERIC_SET_SPARSE_4K;
1388 
1389 		sparse_banks_len =
1390 			bitmap_weight((unsigned long *)&valid_bank_mask, 64) *
1391 			sizeof(sparse_banks[0]);
1392 
1393 		if (!sparse_banks_len && !all_cpus)
1394 			goto ret_success;
1395 
1396 		if (!all_cpus &&
1397 		    kvm_read_guest(kvm,
1398 				   ingpa + offsetof(struct hv_tlb_flush_ex,
1399 						    hv_vp_set.bank_contents),
1400 				   sparse_banks,
1401 				   sparse_banks_len))
1402 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
1403 	}
1404 
1405 	cpumask_clear(&hv_vcpu->tlb_flush);
1406 
1407 	vcpu_mask = all_cpus ? NULL :
1408 		sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask,
1409 					vp_bitmap, vcpu_bitmap);
1410 
1411 	/*
1412 	 * vcpu->arch.cr3 may not be up-to-date for running vCPUs so we can't
1413 	 * analyze it here, flush TLB regardless of the specified address space.
1414 	 */
1415 	kvm_make_vcpus_request_mask(kvm,
1416 				    KVM_REQ_TLB_FLUSH | KVM_REQUEST_NO_WAKEUP,
1417 				    vcpu_mask, &hv_vcpu->tlb_flush);
1418 
1419 ret_success:
1420 	/* We always do full TLB flush, set rep_done = rep_cnt. */
1421 	return (u64)HV_STATUS_SUCCESS |
1422 		((u64)rep_cnt << HV_HYPERCALL_REP_COMP_OFFSET);
1423 }
1424 
1425 static void kvm_send_ipi_to_many(struct kvm *kvm, u32 vector,
1426 				 unsigned long *vcpu_bitmap)
1427 {
1428 	struct kvm_lapic_irq irq = {
1429 		.delivery_mode = APIC_DM_FIXED,
1430 		.vector = vector
1431 	};
1432 	struct kvm_vcpu *vcpu;
1433 	int i;
1434 
1435 	kvm_for_each_vcpu(i, vcpu, kvm) {
1436 		if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
1437 			continue;
1438 
1439 		/* We fail only when APIC is disabled */
1440 		kvm_apic_set_irq(vcpu, &irq, NULL);
1441 	}
1442 }
1443 
1444 static u64 kvm_hv_send_ipi(struct kvm_vcpu *current_vcpu, u64 ingpa, u64 outgpa,
1445 			   bool ex, bool fast)
1446 {
1447 	struct kvm *kvm = current_vcpu->kvm;
1448 	struct hv_send_ipi_ex send_ipi_ex;
1449 	struct hv_send_ipi send_ipi;
1450 	u64 vp_bitmap[KVM_HV_MAX_SPARSE_VCPU_SET_BITS];
1451 	DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
1452 	unsigned long *vcpu_mask;
1453 	unsigned long valid_bank_mask;
1454 	u64 sparse_banks[64];
1455 	int sparse_banks_len;
1456 	u32 vector;
1457 	bool all_cpus;
1458 
1459 	if (!ex) {
1460 		if (!fast) {
1461 			if (unlikely(kvm_read_guest(kvm, ingpa, &send_ipi,
1462 						    sizeof(send_ipi))))
1463 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
1464 			sparse_banks[0] = send_ipi.cpu_mask;
1465 			vector = send_ipi.vector;
1466 		} else {
1467 			/* 'reserved' part of hv_send_ipi should be 0 */
1468 			if (unlikely(ingpa >> 32 != 0))
1469 				return HV_STATUS_INVALID_HYPERCALL_INPUT;
1470 			sparse_banks[0] = outgpa;
1471 			vector = (u32)ingpa;
1472 		}
1473 		all_cpus = false;
1474 		valid_bank_mask = BIT_ULL(0);
1475 
1476 		trace_kvm_hv_send_ipi(vector, sparse_banks[0]);
1477 	} else {
1478 		if (unlikely(kvm_read_guest(kvm, ingpa, &send_ipi_ex,
1479 					    sizeof(send_ipi_ex))))
1480 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
1481 
1482 		trace_kvm_hv_send_ipi_ex(send_ipi_ex.vector,
1483 					 send_ipi_ex.vp_set.format,
1484 					 send_ipi_ex.vp_set.valid_bank_mask);
1485 
1486 		vector = send_ipi_ex.vector;
1487 		valid_bank_mask = send_ipi_ex.vp_set.valid_bank_mask;
1488 		sparse_banks_len = bitmap_weight(&valid_bank_mask, 64) *
1489 			sizeof(sparse_banks[0]);
1490 
1491 		all_cpus = send_ipi_ex.vp_set.format == HV_GENERIC_SET_ALL;
1492 
1493 		if (!sparse_banks_len)
1494 			goto ret_success;
1495 
1496 		if (!all_cpus &&
1497 		    kvm_read_guest(kvm,
1498 				   ingpa + offsetof(struct hv_send_ipi_ex,
1499 						    vp_set.bank_contents),
1500 				   sparse_banks,
1501 				   sparse_banks_len))
1502 			return HV_STATUS_INVALID_HYPERCALL_INPUT;
1503 	}
1504 
1505 	if ((vector < HV_IPI_LOW_VECTOR) || (vector > HV_IPI_HIGH_VECTOR))
1506 		return HV_STATUS_INVALID_HYPERCALL_INPUT;
1507 
1508 	vcpu_mask = all_cpus ? NULL :
1509 		sparse_set_to_vcpu_mask(kvm, sparse_banks, valid_bank_mask,
1510 					vp_bitmap, vcpu_bitmap);
1511 
1512 	kvm_send_ipi_to_many(kvm, vector, vcpu_mask);
1513 
1514 ret_success:
1515 	return HV_STATUS_SUCCESS;
1516 }
1517 
1518 bool kvm_hv_hypercall_enabled(struct kvm *kvm)
1519 {
1520 	return READ_ONCE(kvm->arch.hyperv.hv_hypercall) & HV_X64_MSR_HYPERCALL_ENABLE;
1521 }
1522 
1523 static void kvm_hv_hypercall_set_result(struct kvm_vcpu *vcpu, u64 result)
1524 {
1525 	bool longmode;
1526 
1527 	longmode = is_64_bit_mode(vcpu);
1528 	if (longmode)
1529 		kvm_register_write(vcpu, VCPU_REGS_RAX, result);
1530 	else {
1531 		kvm_register_write(vcpu, VCPU_REGS_RDX, result >> 32);
1532 		kvm_register_write(vcpu, VCPU_REGS_RAX, result & 0xffffffff);
1533 	}
1534 }
1535 
1536 static int kvm_hv_hypercall_complete(struct kvm_vcpu *vcpu, u64 result)
1537 {
1538 	kvm_hv_hypercall_set_result(vcpu, result);
1539 	++vcpu->stat.hypercalls;
1540 	return kvm_skip_emulated_instruction(vcpu);
1541 }
1542 
1543 static int kvm_hv_hypercall_complete_userspace(struct kvm_vcpu *vcpu)
1544 {
1545 	return kvm_hv_hypercall_complete(vcpu, vcpu->run->hyperv.u.hcall.result);
1546 }
1547 
1548 static u16 kvm_hvcall_signal_event(struct kvm_vcpu *vcpu, bool fast, u64 param)
1549 {
1550 	struct eventfd_ctx *eventfd;
1551 
1552 	if (unlikely(!fast)) {
1553 		int ret;
1554 		gpa_t gpa = param;
1555 
1556 		if ((gpa & (__alignof__(param) - 1)) ||
1557 		    offset_in_page(gpa) + sizeof(param) > PAGE_SIZE)
1558 			return HV_STATUS_INVALID_ALIGNMENT;
1559 
1560 		ret = kvm_vcpu_read_guest(vcpu, gpa, &param, sizeof(param));
1561 		if (ret < 0)
1562 			return HV_STATUS_INVALID_ALIGNMENT;
1563 	}
1564 
1565 	/*
1566 	 * Per spec, bits 32-47 contain the extra "flag number".  However, we
1567 	 * have no use for it, and in all known usecases it is zero, so just
1568 	 * report lookup failure if it isn't.
1569 	 */
1570 	if (param & 0xffff00000000ULL)
1571 		return HV_STATUS_INVALID_PORT_ID;
1572 	/* remaining bits are reserved-zero */
1573 	if (param & ~KVM_HYPERV_CONN_ID_MASK)
1574 		return HV_STATUS_INVALID_HYPERCALL_INPUT;
1575 
1576 	/* the eventfd is protected by vcpu->kvm->srcu, but conn_to_evt isn't */
1577 	rcu_read_lock();
1578 	eventfd = idr_find(&vcpu->kvm->arch.hyperv.conn_to_evt, param);
1579 	rcu_read_unlock();
1580 	if (!eventfd)
1581 		return HV_STATUS_INVALID_PORT_ID;
1582 
1583 	eventfd_signal(eventfd, 1);
1584 	return HV_STATUS_SUCCESS;
1585 }
1586 
1587 int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
1588 {
1589 	u64 param, ingpa, outgpa, ret = HV_STATUS_SUCCESS;
1590 	uint16_t code, rep_idx, rep_cnt;
1591 	bool fast, longmode, rep;
1592 
1593 	/*
1594 	 * hypercall generates UD from non zero cpl and real mode
1595 	 * per HYPER-V spec
1596 	 */
1597 	if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
1598 		kvm_queue_exception(vcpu, UD_VECTOR);
1599 		return 1;
1600 	}
1601 
1602 	longmode = is_64_bit_mode(vcpu);
1603 
1604 	if (!longmode) {
1605 		param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
1606 			(kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
1607 		ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
1608 			(kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
1609 		outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
1610 			(kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
1611 	}
1612 #ifdef CONFIG_X86_64
1613 	else {
1614 		param = kvm_register_read(vcpu, VCPU_REGS_RCX);
1615 		ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
1616 		outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
1617 	}
1618 #endif
1619 
1620 	code = param & 0xffff;
1621 	fast = !!(param & HV_HYPERCALL_FAST_BIT);
1622 	rep_cnt = (param >> HV_HYPERCALL_REP_COMP_OFFSET) & 0xfff;
1623 	rep_idx = (param >> HV_HYPERCALL_REP_START_OFFSET) & 0xfff;
1624 	rep = !!(rep_cnt || rep_idx);
1625 
1626 	trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
1627 
1628 	switch (code) {
1629 	case HVCALL_NOTIFY_LONG_SPIN_WAIT:
1630 		if (unlikely(rep)) {
1631 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1632 			break;
1633 		}
1634 		kvm_vcpu_on_spin(vcpu, true);
1635 		break;
1636 	case HVCALL_SIGNAL_EVENT:
1637 		if (unlikely(rep)) {
1638 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1639 			break;
1640 		}
1641 		ret = kvm_hvcall_signal_event(vcpu, fast, ingpa);
1642 		if (ret != HV_STATUS_INVALID_PORT_ID)
1643 			break;
1644 		/* fall through - maybe userspace knows this conn_id. */
1645 	case HVCALL_POST_MESSAGE:
1646 		/* don't bother userspace if it has no way to handle it */
1647 		if (unlikely(rep || !vcpu_to_synic(vcpu)->active)) {
1648 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1649 			break;
1650 		}
1651 		vcpu->run->exit_reason = KVM_EXIT_HYPERV;
1652 		vcpu->run->hyperv.type = KVM_EXIT_HYPERV_HCALL;
1653 		vcpu->run->hyperv.u.hcall.input = param;
1654 		vcpu->run->hyperv.u.hcall.params[0] = ingpa;
1655 		vcpu->run->hyperv.u.hcall.params[1] = outgpa;
1656 		vcpu->arch.complete_userspace_io =
1657 				kvm_hv_hypercall_complete_userspace;
1658 		return 0;
1659 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST:
1660 		if (unlikely(fast || !rep_cnt || rep_idx)) {
1661 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1662 			break;
1663 		}
1664 		ret = kvm_hv_flush_tlb(vcpu, ingpa, rep_cnt, false);
1665 		break;
1666 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE:
1667 		if (unlikely(fast || rep)) {
1668 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1669 			break;
1670 		}
1671 		ret = kvm_hv_flush_tlb(vcpu, ingpa, rep_cnt, false);
1672 		break;
1673 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_LIST_EX:
1674 		if (unlikely(fast || !rep_cnt || rep_idx)) {
1675 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1676 			break;
1677 		}
1678 		ret = kvm_hv_flush_tlb(vcpu, ingpa, rep_cnt, true);
1679 		break;
1680 	case HVCALL_FLUSH_VIRTUAL_ADDRESS_SPACE_EX:
1681 		if (unlikely(fast || rep)) {
1682 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1683 			break;
1684 		}
1685 		ret = kvm_hv_flush_tlb(vcpu, ingpa, rep_cnt, true);
1686 		break;
1687 	case HVCALL_SEND_IPI:
1688 		if (unlikely(rep)) {
1689 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1690 			break;
1691 		}
1692 		ret = kvm_hv_send_ipi(vcpu, ingpa, outgpa, false, fast);
1693 		break;
1694 	case HVCALL_SEND_IPI_EX:
1695 		if (unlikely(fast || rep)) {
1696 			ret = HV_STATUS_INVALID_HYPERCALL_INPUT;
1697 			break;
1698 		}
1699 		ret = kvm_hv_send_ipi(vcpu, ingpa, outgpa, true, false);
1700 		break;
1701 	default:
1702 		ret = HV_STATUS_INVALID_HYPERCALL_CODE;
1703 		break;
1704 	}
1705 
1706 	return kvm_hv_hypercall_complete(vcpu, ret);
1707 }
1708 
1709 void kvm_hv_init_vm(struct kvm *kvm)
1710 {
1711 	mutex_init(&kvm->arch.hyperv.hv_lock);
1712 	idr_init(&kvm->arch.hyperv.conn_to_evt);
1713 }
1714 
1715 void kvm_hv_destroy_vm(struct kvm *kvm)
1716 {
1717 	struct eventfd_ctx *eventfd;
1718 	int i;
1719 
1720 	idr_for_each_entry(&kvm->arch.hyperv.conn_to_evt, eventfd, i)
1721 		eventfd_ctx_put(eventfd);
1722 	idr_destroy(&kvm->arch.hyperv.conn_to_evt);
1723 }
1724 
1725 static int kvm_hv_eventfd_assign(struct kvm *kvm, u32 conn_id, int fd)
1726 {
1727 	struct kvm_hv *hv = &kvm->arch.hyperv;
1728 	struct eventfd_ctx *eventfd;
1729 	int ret;
1730 
1731 	eventfd = eventfd_ctx_fdget(fd);
1732 	if (IS_ERR(eventfd))
1733 		return PTR_ERR(eventfd);
1734 
1735 	mutex_lock(&hv->hv_lock);
1736 	ret = idr_alloc(&hv->conn_to_evt, eventfd, conn_id, conn_id + 1,
1737 			GFP_KERNEL_ACCOUNT);
1738 	mutex_unlock(&hv->hv_lock);
1739 
1740 	if (ret >= 0)
1741 		return 0;
1742 
1743 	if (ret == -ENOSPC)
1744 		ret = -EEXIST;
1745 	eventfd_ctx_put(eventfd);
1746 	return ret;
1747 }
1748 
1749 static int kvm_hv_eventfd_deassign(struct kvm *kvm, u32 conn_id)
1750 {
1751 	struct kvm_hv *hv = &kvm->arch.hyperv;
1752 	struct eventfd_ctx *eventfd;
1753 
1754 	mutex_lock(&hv->hv_lock);
1755 	eventfd = idr_remove(&hv->conn_to_evt, conn_id);
1756 	mutex_unlock(&hv->hv_lock);
1757 
1758 	if (!eventfd)
1759 		return -ENOENT;
1760 
1761 	synchronize_srcu(&kvm->srcu);
1762 	eventfd_ctx_put(eventfd);
1763 	return 0;
1764 }
1765 
1766 int kvm_vm_ioctl_hv_eventfd(struct kvm *kvm, struct kvm_hyperv_eventfd *args)
1767 {
1768 	if ((args->flags & ~KVM_HYPERV_EVENTFD_DEASSIGN) ||
1769 	    (args->conn_id & ~KVM_HYPERV_CONN_ID_MASK))
1770 		return -EINVAL;
1771 
1772 	if (args->flags == KVM_HYPERV_EVENTFD_DEASSIGN)
1773 		return kvm_hv_eventfd_deassign(kvm, args->conn_id);
1774 	return kvm_hv_eventfd_assign(kvm, args->conn_id, args->fd);
1775 }
1776 
1777 int kvm_vcpu_ioctl_get_hv_cpuid(struct kvm_vcpu *vcpu, struct kvm_cpuid2 *cpuid,
1778 				struct kvm_cpuid_entry2 __user *entries)
1779 {
1780 	uint16_t evmcs_ver = kvm_x86_ops->nested_get_evmcs_version(vcpu);
1781 	struct kvm_cpuid_entry2 cpuid_entries[] = {
1782 		{ .function = HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS },
1783 		{ .function = HYPERV_CPUID_INTERFACE },
1784 		{ .function = HYPERV_CPUID_VERSION },
1785 		{ .function = HYPERV_CPUID_FEATURES },
1786 		{ .function = HYPERV_CPUID_ENLIGHTMENT_INFO },
1787 		{ .function = HYPERV_CPUID_IMPLEMENT_LIMITS },
1788 		{ .function = HYPERV_CPUID_NESTED_FEATURES },
1789 	};
1790 	int i, nent = ARRAY_SIZE(cpuid_entries);
1791 
1792 	/* Skip NESTED_FEATURES if eVMCS is not supported */
1793 	if (!evmcs_ver)
1794 		--nent;
1795 
1796 	if (cpuid->nent < nent)
1797 		return -E2BIG;
1798 
1799 	if (cpuid->nent > nent)
1800 		cpuid->nent = nent;
1801 
1802 	for (i = 0; i < nent; i++) {
1803 		struct kvm_cpuid_entry2 *ent = &cpuid_entries[i];
1804 		u32 signature[3];
1805 
1806 		switch (ent->function) {
1807 		case HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS:
1808 			memcpy(signature, "Linux KVM Hv", 12);
1809 
1810 			ent->eax = HYPERV_CPUID_NESTED_FEATURES;
1811 			ent->ebx = signature[0];
1812 			ent->ecx = signature[1];
1813 			ent->edx = signature[2];
1814 			break;
1815 
1816 		case HYPERV_CPUID_INTERFACE:
1817 			memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);
1818 			ent->eax = signature[0];
1819 			break;
1820 
1821 		case HYPERV_CPUID_VERSION:
1822 			/*
1823 			 * We implement some Hyper-V 2016 functions so let's use
1824 			 * this version.
1825 			 */
1826 			ent->eax = 0x00003839;
1827 			ent->ebx = 0x000A0000;
1828 			break;
1829 
1830 		case HYPERV_CPUID_FEATURES:
1831 			ent->eax |= HV_X64_MSR_VP_RUNTIME_AVAILABLE;
1832 			ent->eax |= HV_MSR_TIME_REF_COUNT_AVAILABLE;
1833 			ent->eax |= HV_X64_MSR_SYNIC_AVAILABLE;
1834 			ent->eax |= HV_MSR_SYNTIMER_AVAILABLE;
1835 			ent->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;
1836 			ent->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;
1837 			ent->eax |= HV_X64_MSR_VP_INDEX_AVAILABLE;
1838 			ent->eax |= HV_X64_MSR_RESET_AVAILABLE;
1839 			ent->eax |= HV_MSR_REFERENCE_TSC_AVAILABLE;
1840 			ent->eax |= HV_X64_ACCESS_FREQUENCY_MSRS;
1841 			ent->eax |= HV_X64_ACCESS_REENLIGHTENMENT;
1842 
1843 			ent->ebx |= HV_X64_POST_MESSAGES;
1844 			ent->ebx |= HV_X64_SIGNAL_EVENTS;
1845 
1846 			ent->edx |= HV_FEATURE_FREQUENCY_MSRS_AVAILABLE;
1847 			ent->edx |= HV_FEATURE_GUEST_CRASH_MSR_AVAILABLE;
1848 			ent->edx |= HV_STIMER_DIRECT_MODE_AVAILABLE;
1849 
1850 			break;
1851 
1852 		case HYPERV_CPUID_ENLIGHTMENT_INFO:
1853 			ent->eax |= HV_X64_REMOTE_TLB_FLUSH_RECOMMENDED;
1854 			ent->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;
1855 			ent->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;
1856 			ent->eax |= HV_X64_CLUSTER_IPI_RECOMMENDED;
1857 			ent->eax |= HV_X64_EX_PROCESSOR_MASKS_RECOMMENDED;
1858 			if (evmcs_ver)
1859 				ent->eax |= HV_X64_ENLIGHTENED_VMCS_RECOMMENDED;
1860 
1861 			/*
1862 			 * Default number of spinlock retry attempts, matches
1863 			 * HyperV 2016.
1864 			 */
1865 			ent->ebx = 0x00000FFF;
1866 
1867 			break;
1868 
1869 		case HYPERV_CPUID_IMPLEMENT_LIMITS:
1870 			/* Maximum number of virtual processors */
1871 			ent->eax = KVM_MAX_VCPUS;
1872 			/*
1873 			 * Maximum number of logical processors, matches
1874 			 * HyperV 2016.
1875 			 */
1876 			ent->ebx = 64;
1877 
1878 			break;
1879 
1880 		case HYPERV_CPUID_NESTED_FEATURES:
1881 			ent->eax = evmcs_ver;
1882 
1883 			break;
1884 
1885 		default:
1886 			break;
1887 		}
1888 	}
1889 
1890 	if (copy_to_user(entries, cpuid_entries,
1891 			 nent * sizeof(struct kvm_cpuid_entry2)))
1892 		return -EFAULT;
1893 
1894 	return 0;
1895 }
1896