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