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