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