GNU Linux-libre 5.4.274-gnu1
[releases.git] / arch / x86 / kvm / lapic.c
1 // SPDX-License-Identifier: GPL-2.0-only
2
3 /*
4  * Local APIC virtualization
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright (C) 2007 Novell
8  * Copyright (C) 2007 Intel
9  * Copyright 2009 Red Hat, Inc. and/or its affiliates.
10  *
11  * Authors:
12  *   Dor Laor <dor.laor@qumranet.com>
13  *   Gregory Haskins <ghaskins@novell.com>
14  *   Yaozu (Eddie) Dong <eddie.dong@intel.com>
15  *
16  * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
17  */
18
19 #include <linux/kvm_host.h>
20 #include <linux/kvm.h>
21 #include <linux/mm.h>
22 #include <linux/highmem.h>
23 #include <linux/smp.h>
24 #include <linux/hrtimer.h>
25 #include <linux/io.h>
26 #include <linux/export.h>
27 #include <linux/math64.h>
28 #include <linux/slab.h>
29 #include <asm/processor.h>
30 #include <asm/msr.h>
31 #include <asm/page.h>
32 #include <asm/current.h>
33 #include <asm/apicdef.h>
34 #include <asm/delay.h>
35 #include <linux/atomic.h>
36 #include <linux/jump_label.h>
37 #include "kvm_cache_regs.h"
38 #include "irq.h"
39 #include "trace.h"
40 #include "x86.h"
41 #include "cpuid.h"
42 #include "hyperv.h"
43
44 #ifndef CONFIG_X86_64
45 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
46 #else
47 #define mod_64(x, y) ((x) % (y))
48 #endif
49
50 #define PRId64 "d"
51 #define PRIx64 "llx"
52 #define PRIu64 "u"
53 #define PRIo64 "o"
54
55 /* 14 is the version for Xeon and Pentium 8.4.8*/
56 #define APIC_VERSION                    (0x14UL | ((KVM_APIC_LVT_NUM - 1) << 16))
57 #define LAPIC_MMIO_LENGTH               (1 << 12)
58 /* followed define is not in apicdef.h */
59 #define APIC_SHORT_MASK                 0xc0000
60 #define APIC_DEST_NOSHORT               0x0
61 #define APIC_DEST_MASK                  0x800
62 #define MAX_APIC_VECTOR                 256
63 #define APIC_VECTORS_PER_REG            32
64
65 #define APIC_BROADCAST                  0xFF
66 #define X2APIC_BROADCAST                0xFFFFFFFFul
67
68 static bool lapic_timer_advance_dynamic __read_mostly;
69 #define LAPIC_TIMER_ADVANCE_ADJUST_MIN  100     /* clock cycles */
70 #define LAPIC_TIMER_ADVANCE_ADJUST_MAX  10000   /* clock cycles */
71 #define LAPIC_TIMER_ADVANCE_NS_INIT     1000
72 #define LAPIC_TIMER_ADVANCE_NS_MAX     5000
73 /* step-by-step approximation to mitigate fluctuation */
74 #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
75
76 static inline int apic_test_vector(int vec, void *bitmap)
77 {
78         return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
79 }
80
81 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
82 {
83         struct kvm_lapic *apic = vcpu->arch.apic;
84
85         return apic_test_vector(vector, apic->regs + APIC_ISR) ||
86                 apic_test_vector(vector, apic->regs + APIC_IRR);
87 }
88
89 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
90 {
91         return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
92 }
93
94 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
95 {
96         return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
97 }
98
99 struct static_key_deferred apic_hw_disabled __read_mostly;
100 struct static_key_deferred apic_sw_disabled __read_mostly;
101
102 static inline int apic_enabled(struct kvm_lapic *apic)
103 {
104         return kvm_apic_sw_enabled(apic) &&     kvm_apic_hw_enabled(apic);
105 }
106
107 #define LVT_MASK        \
108         (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
109
110 #define LINT_MASK       \
111         (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
112          APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
113
114 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
115 {
116         return apic->vcpu->vcpu_id;
117 }
118
119 bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
120 {
121         return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
122                 (kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
123 }
124 EXPORT_SYMBOL_GPL(kvm_can_post_timer_interrupt);
125
126 static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
127 {
128         return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
129 }
130
131 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
132                 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
133         switch (map->mode) {
134         case KVM_APIC_MODE_X2APIC: {
135                 u32 offset = (dest_id >> 16) * 16;
136                 u32 max_apic_id = map->max_apic_id;
137
138                 if (offset <= max_apic_id) {
139                         u8 cluster_size = min(max_apic_id - offset + 1, 16U);
140
141                         offset = array_index_nospec(offset, map->max_apic_id + 1);
142                         *cluster = &map->phys_map[offset];
143                         *mask = dest_id & (0xffff >> (16 - cluster_size));
144                 } else {
145                         *mask = 0;
146                 }
147
148                 return true;
149                 }
150         case KVM_APIC_MODE_XAPIC_FLAT:
151                 *cluster = map->xapic_flat_map;
152                 *mask = dest_id & 0xff;
153                 return true;
154         case KVM_APIC_MODE_XAPIC_CLUSTER:
155                 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
156                 *mask = dest_id & 0xf;
157                 return true;
158         default:
159                 /* Not optimized. */
160                 return false;
161         }
162 }
163
164 static void kvm_apic_map_free(struct rcu_head *rcu)
165 {
166         struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
167
168         kvfree(map);
169 }
170
171 static void recalculate_apic_map(struct kvm *kvm)
172 {
173         struct kvm_apic_map *new, *old = NULL;
174         struct kvm_vcpu *vcpu;
175         int i;
176         u32 max_id = 255; /* enough space for any xAPIC ID */
177
178         mutex_lock(&kvm->arch.apic_map_lock);
179
180         kvm_for_each_vcpu(i, vcpu, kvm)
181                 if (kvm_apic_present(vcpu))
182                         max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
183
184         new = kvzalloc(sizeof(struct kvm_apic_map) +
185                            sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
186                            GFP_KERNEL_ACCOUNT);
187
188         if (!new)
189                 goto out;
190
191         new->max_apic_id = max_id;
192
193         kvm_for_each_vcpu(i, vcpu, kvm) {
194                 struct kvm_lapic *apic = vcpu->arch.apic;
195                 struct kvm_lapic **cluster;
196                 u16 mask;
197                 u32 ldr;
198                 u8 xapic_id;
199                 u32 x2apic_id;
200
201                 if (!kvm_apic_present(vcpu))
202                         continue;
203
204                 xapic_id = kvm_xapic_id(apic);
205                 x2apic_id = kvm_x2apic_id(apic);
206
207                 /* Hotplug hack: see kvm_apic_match_physical_addr(), ... */
208                 if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
209                                 x2apic_id <= new->max_apic_id)
210                         new->phys_map[x2apic_id] = apic;
211                 /*
212                  * ... xAPIC ID of VCPUs with APIC ID > 0xff will wrap-around,
213                  * prevent them from masking VCPUs with APIC ID <= 0xff.
214                  */
215                 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
216                         new->phys_map[xapic_id] = apic;
217
218                 if (!kvm_apic_sw_enabled(apic))
219                         continue;
220
221                 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
222
223                 if (apic_x2apic_mode(apic)) {
224                         new->mode |= KVM_APIC_MODE_X2APIC;
225                 } else if (ldr) {
226                         ldr = GET_APIC_LOGICAL_ID(ldr);
227                         if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
228                                 new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
229                         else
230                                 new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
231                 }
232
233                 if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
234                         continue;
235
236                 if (mask)
237                         cluster[ffs(mask) - 1] = apic;
238         }
239 out:
240         old = rcu_dereference_protected(kvm->arch.apic_map,
241                         lockdep_is_held(&kvm->arch.apic_map_lock));
242         rcu_assign_pointer(kvm->arch.apic_map, new);
243         mutex_unlock(&kvm->arch.apic_map_lock);
244
245         if (old)
246                 call_rcu(&old->rcu, kvm_apic_map_free);
247
248         kvm_make_scan_ioapic_request(kvm);
249 }
250
251 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
252 {
253         bool enabled = val & APIC_SPIV_APIC_ENABLED;
254
255         kvm_lapic_set_reg(apic, APIC_SPIV, val);
256
257         if (enabled != apic->sw_enabled) {
258                 apic->sw_enabled = enabled;
259                 if (enabled)
260                         static_key_slow_dec_deferred(&apic_sw_disabled);
261                 else
262                         static_key_slow_inc(&apic_sw_disabled.key);
263
264                 recalculate_apic_map(apic->vcpu->kvm);
265         }
266 }
267
268 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
269 {
270         kvm_lapic_set_reg(apic, APIC_ID, id << 24);
271         recalculate_apic_map(apic->vcpu->kvm);
272 }
273
274 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
275 {
276         kvm_lapic_set_reg(apic, APIC_LDR, id);
277         recalculate_apic_map(apic->vcpu->kvm);
278 }
279
280 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
281 {
282         return ((id >> 4) << 16) | (1 << (id & 0xf));
283 }
284
285 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
286 {
287         u32 ldr = kvm_apic_calc_x2apic_ldr(id);
288
289         WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
290
291         kvm_lapic_set_reg(apic, APIC_ID, id);
292         kvm_lapic_set_reg(apic, APIC_LDR, ldr);
293         recalculate_apic_map(apic->vcpu->kvm);
294 }
295
296 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
297 {
298         return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
299 }
300
301 static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
302 {
303         return kvm_lapic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
304 }
305
306 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
307 {
308         return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
309 }
310
311 static inline int apic_lvtt_period(struct kvm_lapic *apic)
312 {
313         return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
314 }
315
316 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
317 {
318         return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
319 }
320
321 static inline int apic_lvt_nmi_mode(u32 lvt_val)
322 {
323         return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
324 }
325
326 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
327 {
328         struct kvm_lapic *apic = vcpu->arch.apic;
329         struct kvm_cpuid_entry2 *feat;
330         u32 v = APIC_VERSION;
331
332         if (!lapic_in_kernel(vcpu))
333                 return;
334
335         /*
336          * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
337          * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
338          * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
339          * version first and level-triggered interrupts never get EOIed in
340          * IOAPIC.
341          */
342         feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
343         if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))) &&
344             !ioapic_in_kernel(vcpu->kvm))
345                 v |= APIC_LVR_DIRECTED_EOI;
346         kvm_lapic_set_reg(apic, APIC_LVR, v);
347 }
348
349 static const unsigned int apic_lvt_mask[KVM_APIC_LVT_NUM] = {
350         LVT_MASK ,      /* part LVTT mask, timer mode mask added at runtime */
351         LVT_MASK | APIC_MODE_MASK,      /* LVTTHMR */
352         LVT_MASK | APIC_MODE_MASK,      /* LVTPC */
353         LINT_MASK, LINT_MASK,   /* LVT0-1 */
354         LVT_MASK                /* LVTERR */
355 };
356
357 static int find_highest_vector(void *bitmap)
358 {
359         int vec;
360         u32 *reg;
361
362         for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
363              vec >= 0; vec -= APIC_VECTORS_PER_REG) {
364                 reg = bitmap + REG_POS(vec);
365                 if (*reg)
366                         return __fls(*reg) + vec;
367         }
368
369         return -1;
370 }
371
372 static u8 count_vectors(void *bitmap)
373 {
374         int vec;
375         u32 *reg;
376         u8 count = 0;
377
378         for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
379                 reg = bitmap + REG_POS(vec);
380                 count += hweight32(*reg);
381         }
382
383         return count;
384 }
385
386 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
387 {
388         u32 i, vec;
389         u32 pir_val, irr_val, prev_irr_val;
390         int max_updated_irr;
391
392         max_updated_irr = -1;
393         *max_irr = -1;
394
395         for (i = vec = 0; i <= 7; i++, vec += 32) {
396                 pir_val = READ_ONCE(pir[i]);
397                 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
398                 if (pir_val) {
399                         prev_irr_val = irr_val;
400                         irr_val |= xchg(&pir[i], 0);
401                         *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
402                         if (prev_irr_val != irr_val) {
403                                 max_updated_irr =
404                                         __fls(irr_val ^ prev_irr_val) + vec;
405                         }
406                 }
407                 if (irr_val)
408                         *max_irr = __fls(irr_val) + vec;
409         }
410
411         return ((max_updated_irr != -1) &&
412                 (max_updated_irr == *max_irr));
413 }
414 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
415
416 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
417 {
418         struct kvm_lapic *apic = vcpu->arch.apic;
419
420         return __kvm_apic_update_irr(pir, apic->regs, max_irr);
421 }
422 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
423
424 static inline int apic_search_irr(struct kvm_lapic *apic)
425 {
426         return find_highest_vector(apic->regs + APIC_IRR);
427 }
428
429 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
430 {
431         int result;
432
433         /*
434          * Note that irr_pending is just a hint. It will be always
435          * true with virtual interrupt delivery enabled.
436          */
437         if (!apic->irr_pending)
438                 return -1;
439
440         result = apic_search_irr(apic);
441         ASSERT(result == -1 || result >= 16);
442
443         return result;
444 }
445
446 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
447 {
448         struct kvm_vcpu *vcpu;
449
450         vcpu = apic->vcpu;
451
452         if (unlikely(vcpu->arch.apicv_active)) {
453                 /* need to update RVI */
454                 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
455                 kvm_x86_ops->hwapic_irr_update(vcpu,
456                                 apic_find_highest_irr(apic));
457         } else {
458                 apic->irr_pending = false;
459                 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
460                 if (apic_search_irr(apic) != -1)
461                         apic->irr_pending = true;
462         }
463 }
464
465 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
466 {
467         struct kvm_vcpu *vcpu;
468
469         if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
470                 return;
471
472         vcpu = apic->vcpu;
473
474         /*
475          * With APIC virtualization enabled, all caching is disabled
476          * because the processor can modify ISR under the hood.  Instead
477          * just set SVI.
478          */
479         if (unlikely(vcpu->arch.apicv_active))
480                 kvm_x86_ops->hwapic_isr_update(vcpu, vec);
481         else {
482                 ++apic->isr_count;
483                 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
484                 /*
485                  * ISR (in service register) bit is set when injecting an interrupt.
486                  * The highest vector is injected. Thus the latest bit set matches
487                  * the highest bit in ISR.
488                  */
489                 apic->highest_isr_cache = vec;
490         }
491 }
492
493 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
494 {
495         int result;
496
497         /*
498          * Note that isr_count is always 1, and highest_isr_cache
499          * is always -1, with APIC virtualization enabled.
500          */
501         if (!apic->isr_count)
502                 return -1;
503         if (likely(apic->highest_isr_cache != -1))
504                 return apic->highest_isr_cache;
505
506         result = find_highest_vector(apic->regs + APIC_ISR);
507         ASSERT(result == -1 || result >= 16);
508
509         return result;
510 }
511
512 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
513 {
514         struct kvm_vcpu *vcpu;
515         if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
516                 return;
517
518         vcpu = apic->vcpu;
519
520         /*
521          * We do get here for APIC virtualization enabled if the guest
522          * uses the Hyper-V APIC enlightenment.  In this case we may need
523          * to trigger a new interrupt delivery by writing the SVI field;
524          * on the other hand isr_count and highest_isr_cache are unused
525          * and must be left alone.
526          */
527         if (unlikely(vcpu->arch.apicv_active))
528                 kvm_x86_ops->hwapic_isr_update(vcpu,
529                                                apic_find_highest_isr(apic));
530         else {
531                 --apic->isr_count;
532                 BUG_ON(apic->isr_count < 0);
533                 apic->highest_isr_cache = -1;
534         }
535 }
536
537 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
538 {
539         /* This may race with setting of irr in __apic_accept_irq() and
540          * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
541          * will cause vmexit immediately and the value will be recalculated
542          * on the next vmentry.
543          */
544         return apic_find_highest_irr(vcpu->arch.apic);
545 }
546 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
547
548 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
549                              int vector, int level, int trig_mode,
550                              struct dest_map *dest_map);
551
552 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
553                      struct dest_map *dest_map)
554 {
555         struct kvm_lapic *apic = vcpu->arch.apic;
556
557         return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
558                         irq->level, irq->trig_mode, dest_map);
559 }
560
561 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
562                     unsigned long ipi_bitmap_high, u32 min,
563                     unsigned long icr, int op_64_bit)
564 {
565         int i;
566         struct kvm_apic_map *map;
567         struct kvm_vcpu *vcpu;
568         struct kvm_lapic_irq irq = {0};
569         int cluster_size = op_64_bit ? 64 : 32;
570         int count = 0;
571
572         irq.vector = icr & APIC_VECTOR_MASK;
573         irq.delivery_mode = icr & APIC_MODE_MASK;
574         irq.level = (icr & APIC_INT_ASSERT) != 0;
575         irq.trig_mode = icr & APIC_INT_LEVELTRIG;
576
577         if (icr & APIC_DEST_MASK)
578                 return -KVM_EINVAL;
579         if (icr & APIC_SHORT_MASK)
580                 return -KVM_EINVAL;
581
582         rcu_read_lock();
583         map = rcu_dereference(kvm->arch.apic_map);
584
585         if (unlikely(!map)) {
586                 count = -EOPNOTSUPP;
587                 goto out;
588         }
589
590         if (min > map->max_apic_id)
591                 goto out;
592         /* Bits above cluster_size are masked in the caller.  */
593         for_each_set_bit(i, &ipi_bitmap_low,
594                 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
595                 if (map->phys_map[min + i]) {
596                         vcpu = map->phys_map[min + i]->vcpu;
597                         count += kvm_apic_set_irq(vcpu, &irq, NULL);
598                 }
599         }
600
601         min += cluster_size;
602
603         if (min > map->max_apic_id)
604                 goto out;
605
606         for_each_set_bit(i, &ipi_bitmap_high,
607                 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
608                 if (map->phys_map[min + i]) {
609                         vcpu = map->phys_map[min + i]->vcpu;
610                         count += kvm_apic_set_irq(vcpu, &irq, NULL);
611                 }
612         }
613
614 out:
615         rcu_read_unlock();
616         return count;
617 }
618
619 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
620 {
621
622         return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
623                                       sizeof(val));
624 }
625
626 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
627 {
628
629         return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
630                                       sizeof(*val));
631 }
632
633 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
634 {
635         return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
636 }
637
638 static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
639 {
640         u8 val;
641         if (pv_eoi_get_user(vcpu, &val) < 0) {
642                 printk(KERN_WARNING "Can't read EOI MSR value: 0x%llx\n",
643                            (unsigned long long)vcpu->arch.pv_eoi.msr_val);
644                 return false;
645         }
646         return val & 0x1;
647 }
648
649 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
650 {
651         if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
652                 printk(KERN_WARNING "Can't set EOI MSR value: 0x%llx\n",
653                            (unsigned long long)vcpu->arch.pv_eoi.msr_val);
654                 return;
655         }
656         __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
657 }
658
659 static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
660 {
661         if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
662                 printk(KERN_WARNING "Can't clear EOI MSR value: 0x%llx\n",
663                            (unsigned long long)vcpu->arch.pv_eoi.msr_val);
664                 return;
665         }
666         __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
667 }
668
669 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
670 {
671         int highest_irr;
672         if (apic->vcpu->arch.apicv_active)
673                 highest_irr = kvm_x86_ops->sync_pir_to_irr(apic->vcpu);
674         else
675                 highest_irr = apic_find_highest_irr(apic);
676         if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
677                 return -1;
678         return highest_irr;
679 }
680
681 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
682 {
683         u32 tpr, isrv, ppr, old_ppr;
684         int isr;
685
686         old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
687         tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
688         isr = apic_find_highest_isr(apic);
689         isrv = (isr != -1) ? isr : 0;
690
691         if ((tpr & 0xf0) >= (isrv & 0xf0))
692                 ppr = tpr & 0xff;
693         else
694                 ppr = isrv & 0xf0;
695
696         *new_ppr = ppr;
697         if (old_ppr != ppr)
698                 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
699
700         return ppr < old_ppr;
701 }
702
703 static void apic_update_ppr(struct kvm_lapic *apic)
704 {
705         u32 ppr;
706
707         if (__apic_update_ppr(apic, &ppr) &&
708             apic_has_interrupt_for_ppr(apic, ppr) != -1)
709                 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
710 }
711
712 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
713 {
714         apic_update_ppr(vcpu->arch.apic);
715 }
716 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
717
718 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
719 {
720         kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
721         apic_update_ppr(apic);
722 }
723
724 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
725 {
726         return mda == (apic_x2apic_mode(apic) ?
727                         X2APIC_BROADCAST : APIC_BROADCAST);
728 }
729
730 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
731 {
732         if (kvm_apic_broadcast(apic, mda))
733                 return true;
734
735         if (apic_x2apic_mode(apic))
736                 return mda == kvm_x2apic_id(apic);
737
738         /*
739          * Hotplug hack: Make LAPIC in xAPIC mode also accept interrupts as if
740          * it were in x2APIC mode.  Hotplugged VCPUs start in xAPIC mode and
741          * this allows unique addressing of VCPUs with APIC ID over 0xff.
742          * The 0xff condition is needed because writeable xAPIC ID.
743          */
744         if (kvm_x2apic_id(apic) > 0xff && mda == kvm_x2apic_id(apic))
745                 return true;
746
747         return mda == kvm_xapic_id(apic);
748 }
749
750 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
751 {
752         u32 logical_id;
753
754         if (kvm_apic_broadcast(apic, mda))
755                 return true;
756
757         logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
758
759         if (apic_x2apic_mode(apic))
760                 return ((logical_id >> 16) == (mda >> 16))
761                        && (logical_id & mda & 0xffff) != 0;
762
763         logical_id = GET_APIC_LOGICAL_ID(logical_id);
764
765         switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
766         case APIC_DFR_FLAT:
767                 return (logical_id & mda) != 0;
768         case APIC_DFR_CLUSTER:
769                 return ((logical_id >> 4) == (mda >> 4))
770                        && (logical_id & mda & 0xf) != 0;
771         default:
772                 return false;
773         }
774 }
775
776 /* The KVM local APIC implementation has two quirks:
777  *
778  *  - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
779  *    in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
780  *    KVM doesn't do that aliasing.
781  *
782  *  - in-kernel IOAPIC messages have to be delivered directly to
783  *    x2APIC, because the kernel does not support interrupt remapping.
784  *    In order to support broadcast without interrupt remapping, x2APIC
785  *    rewrites the destination of non-IPI messages from APIC_BROADCAST
786  *    to X2APIC_BROADCAST.
787  *
788  * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API.  This is
789  * important when userspace wants to use x2APIC-format MSIs, because
790  * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
791  */
792 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
793                 struct kvm_lapic *source, struct kvm_lapic *target)
794 {
795         bool ipi = source != NULL;
796
797         if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
798             !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
799                 return X2APIC_BROADCAST;
800
801         return dest_id;
802 }
803
804 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
805                            int short_hand, unsigned int dest, int dest_mode)
806 {
807         struct kvm_lapic *target = vcpu->arch.apic;
808         u32 mda = kvm_apic_mda(vcpu, dest, source, target);
809
810         ASSERT(target);
811         switch (short_hand) {
812         case APIC_DEST_NOSHORT:
813                 if (dest_mode == APIC_DEST_PHYSICAL)
814                         return kvm_apic_match_physical_addr(target, mda);
815                 else
816                         return kvm_apic_match_logical_addr(target, mda);
817         case APIC_DEST_SELF:
818                 return target == source;
819         case APIC_DEST_ALLINC:
820                 return true;
821         case APIC_DEST_ALLBUT:
822                 return target != source;
823         default:
824                 return false;
825         }
826 }
827 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
828
829 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
830                        const unsigned long *bitmap, u32 bitmap_size)
831 {
832         u32 mod;
833         int i, idx = -1;
834
835         mod = vector % dest_vcpus;
836
837         for (i = 0; i <= mod; i++) {
838                 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
839                 BUG_ON(idx == bitmap_size);
840         }
841
842         return idx;
843 }
844
845 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
846 {
847         if (!kvm->arch.disabled_lapic_found) {
848                 kvm->arch.disabled_lapic_found = true;
849                 printk(KERN_INFO
850                        "Disabled LAPIC found during irq injection\n");
851         }
852 }
853
854 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
855                 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
856 {
857         if (kvm->arch.x2apic_broadcast_quirk_disabled) {
858                 if ((irq->dest_id == APIC_BROADCAST &&
859                                 map->mode != KVM_APIC_MODE_X2APIC))
860                         return true;
861                 if (irq->dest_id == X2APIC_BROADCAST)
862                         return true;
863         } else {
864                 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
865                 if (irq->dest_id == (x2apic_ipi ?
866                                      X2APIC_BROADCAST : APIC_BROADCAST))
867                         return true;
868         }
869
870         return false;
871 }
872
873 /* Return true if the interrupt can be handled by using *bitmap as index mask
874  * for valid destinations in *dst array.
875  * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
876  * Note: we may have zero kvm_lapic destinations when we return true, which
877  * means that the interrupt should be dropped.  In this case, *bitmap would be
878  * zero and *dst undefined.
879  */
880 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
881                 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
882                 struct kvm_apic_map *map, struct kvm_lapic ***dst,
883                 unsigned long *bitmap)
884 {
885         int i, lowest;
886
887         if (irq->shorthand == APIC_DEST_SELF && src) {
888                 *dst = src;
889                 *bitmap = 1;
890                 return true;
891         } else if (irq->shorthand)
892                 return false;
893
894         if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
895                 return false;
896
897         if (irq->dest_mode == APIC_DEST_PHYSICAL) {
898                 if (irq->dest_id > map->max_apic_id) {
899                         *bitmap = 0;
900                 } else {
901                         u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
902                         *dst = &map->phys_map[dest_id];
903                         *bitmap = 1;
904                 }
905                 return true;
906         }
907
908         *bitmap = 0;
909         if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
910                                 (u16 *)bitmap))
911                 return false;
912
913         if (!kvm_lowest_prio_delivery(irq))
914                 return true;
915
916         if (!kvm_vector_hashing_enabled()) {
917                 lowest = -1;
918                 for_each_set_bit(i, bitmap, 16) {
919                         if (!(*dst)[i])
920                                 continue;
921                         if (lowest < 0)
922                                 lowest = i;
923                         else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
924                                                 (*dst)[lowest]->vcpu) < 0)
925                                 lowest = i;
926                 }
927         } else {
928                 if (!*bitmap)
929                         return true;
930
931                 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
932                                 bitmap, 16);
933
934                 if (!(*dst)[lowest]) {
935                         kvm_apic_disabled_lapic_found(kvm);
936                         *bitmap = 0;
937                         return true;
938                 }
939         }
940
941         *bitmap = (lowest >= 0) ? 1 << lowest : 0;
942
943         return true;
944 }
945
946 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
947                 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
948 {
949         struct kvm_apic_map *map;
950         unsigned long bitmap;
951         struct kvm_lapic **dst = NULL;
952         int i;
953         bool ret;
954
955         *r = -1;
956
957         if (irq->shorthand == APIC_DEST_SELF) {
958                 if (KVM_BUG_ON(!src, kvm)) {
959                         *r = 0;
960                         return true;
961                 }
962                 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
963                 return true;
964         }
965
966         rcu_read_lock();
967         map = rcu_dereference(kvm->arch.apic_map);
968
969         ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
970         if (ret) {
971                 *r = 0;
972                 for_each_set_bit(i, &bitmap, 16) {
973                         if (!dst[i])
974                                 continue;
975                         *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
976                 }
977         }
978
979         rcu_read_unlock();
980         return ret;
981 }
982
983 /*
984  * This routine tries to handler interrupts in posted mode, here is how
985  * it deals with different cases:
986  * - For single-destination interrupts, handle it in posted mode
987  * - Else if vector hashing is enabled and it is a lowest-priority
988  *   interrupt, handle it in posted mode and use the following mechanism
989  *   to find the destinaiton vCPU.
990  *      1. For lowest-priority interrupts, store all the possible
991  *         destination vCPUs in an array.
992  *      2. Use "guest vector % max number of destination vCPUs" to find
993  *         the right destination vCPU in the array for the lowest-priority
994  *         interrupt.
995  * - Otherwise, use remapped mode to inject the interrupt.
996  */
997 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
998                         struct kvm_vcpu **dest_vcpu)
999 {
1000         struct kvm_apic_map *map;
1001         unsigned long bitmap;
1002         struct kvm_lapic **dst = NULL;
1003         bool ret = false;
1004
1005         if (irq->shorthand)
1006                 return false;
1007
1008         rcu_read_lock();
1009         map = rcu_dereference(kvm->arch.apic_map);
1010
1011         if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1012                         hweight16(bitmap) == 1) {
1013                 unsigned long i = find_first_bit(&bitmap, 16);
1014
1015                 if (dst[i]) {
1016                         *dest_vcpu = dst[i]->vcpu;
1017                         ret = true;
1018                 }
1019         }
1020
1021         rcu_read_unlock();
1022         return ret;
1023 }
1024
1025 /*
1026  * Add a pending IRQ into lapic.
1027  * Return 1 if successfully added and 0 if discarded.
1028  */
1029 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1030                              int vector, int level, int trig_mode,
1031                              struct dest_map *dest_map)
1032 {
1033         int result = 0;
1034         struct kvm_vcpu *vcpu = apic->vcpu;
1035
1036         trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1037                                   trig_mode, vector);
1038         switch (delivery_mode) {
1039         case APIC_DM_LOWEST:
1040                 vcpu->arch.apic_arb_prio++;
1041                 /* fall through */
1042         case APIC_DM_FIXED:
1043                 if (unlikely(trig_mode && !level))
1044                         break;
1045
1046                 /* FIXME add logic for vcpu on reset */
1047                 if (unlikely(!apic_enabled(apic)))
1048                         break;
1049
1050                 result = 1;
1051
1052                 if (dest_map) {
1053                         __set_bit(vcpu->vcpu_id, dest_map->map);
1054                         dest_map->vectors[vcpu->vcpu_id] = vector;
1055                 }
1056
1057                 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1058                         if (trig_mode)
1059                                 kvm_lapic_set_vector(vector,
1060                                                      apic->regs + APIC_TMR);
1061                         else
1062                                 kvm_lapic_clear_vector(vector,
1063                                                        apic->regs + APIC_TMR);
1064                 }
1065
1066                 if (kvm_x86_ops->deliver_posted_interrupt(vcpu, vector)) {
1067                         kvm_lapic_set_irr(vector, apic);
1068                         kvm_make_request(KVM_REQ_EVENT, vcpu);
1069                         kvm_vcpu_kick(vcpu);
1070                 }
1071                 break;
1072
1073         case APIC_DM_REMRD:
1074                 result = 1;
1075                 vcpu->arch.pv.pv_unhalted = 1;
1076                 kvm_make_request(KVM_REQ_EVENT, vcpu);
1077                 kvm_vcpu_kick(vcpu);
1078                 break;
1079
1080         case APIC_DM_SMI:
1081                 result = 1;
1082                 kvm_make_request(KVM_REQ_SMI, vcpu);
1083                 kvm_vcpu_kick(vcpu);
1084                 break;
1085
1086         case APIC_DM_NMI:
1087                 result = 1;
1088                 kvm_inject_nmi(vcpu);
1089                 kvm_vcpu_kick(vcpu);
1090                 break;
1091
1092         case APIC_DM_INIT:
1093                 if (!trig_mode || level) {
1094                         result = 1;
1095                         /* assumes that there are only KVM_APIC_INIT/SIPI */
1096                         apic->pending_events = (1UL << KVM_APIC_INIT);
1097                         /* make sure pending_events is visible before sending
1098                          * the request */
1099                         smp_wmb();
1100                         kvm_make_request(KVM_REQ_EVENT, vcpu);
1101                         kvm_vcpu_kick(vcpu);
1102                 }
1103                 break;
1104
1105         case APIC_DM_STARTUP:
1106                 result = 1;
1107                 apic->sipi_vector = vector;
1108                 /* make sure sipi_vector is visible for the receiver */
1109                 smp_wmb();
1110                 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1111                 kvm_make_request(KVM_REQ_EVENT, vcpu);
1112                 kvm_vcpu_kick(vcpu);
1113                 break;
1114
1115         case APIC_DM_EXTINT:
1116                 /*
1117                  * Should only be called by kvm_apic_local_deliver() with LVT0,
1118                  * before NMI watchdog was enabled. Already handled by
1119                  * kvm_apic_accept_pic_intr().
1120                  */
1121                 break;
1122
1123         default:
1124                 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1125                        delivery_mode);
1126                 break;
1127         }
1128         return result;
1129 }
1130
1131 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1132 {
1133         return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1134 }
1135
1136 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1137 {
1138         return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1139 }
1140
1141 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1142 {
1143         int trigger_mode;
1144
1145         /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1146         if (!kvm_ioapic_handles_vector(apic, vector))
1147                 return;
1148
1149         /* Request a KVM exit to inform the userspace IOAPIC. */
1150         if (irqchip_split(apic->vcpu->kvm)) {
1151                 apic->vcpu->arch.pending_ioapic_eoi = vector;
1152                 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1153                 return;
1154         }
1155
1156         if (apic_test_vector(vector, apic->regs + APIC_TMR))
1157                 trigger_mode = IOAPIC_LEVEL_TRIG;
1158         else
1159                 trigger_mode = IOAPIC_EDGE_TRIG;
1160
1161         kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1162 }
1163
1164 static int apic_set_eoi(struct kvm_lapic *apic)
1165 {
1166         int vector = apic_find_highest_isr(apic);
1167
1168         trace_kvm_eoi(apic, vector);
1169
1170         /*
1171          * Not every write EOI will has corresponding ISR,
1172          * one example is when Kernel check timer on setup_IO_APIC
1173          */
1174         if (vector == -1)
1175                 return vector;
1176
1177         apic_clear_isr(vector, apic);
1178         apic_update_ppr(apic);
1179
1180         if (test_bit(vector, vcpu_to_synic(apic->vcpu)->vec_bitmap))
1181                 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1182
1183         kvm_ioapic_send_eoi(apic, vector);
1184         kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1185         return vector;
1186 }
1187
1188 /*
1189  * this interface assumes a trap-like exit, which has already finished
1190  * desired side effect including vISR and vPPR update.
1191  */
1192 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1193 {
1194         struct kvm_lapic *apic = vcpu->arch.apic;
1195
1196         trace_kvm_eoi(apic, vector);
1197
1198         kvm_ioapic_send_eoi(apic, vector);
1199         kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1200 }
1201 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1202
1203 static void apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1204 {
1205         struct kvm_lapic_irq irq;
1206
1207         irq.vector = icr_low & APIC_VECTOR_MASK;
1208         irq.delivery_mode = icr_low & APIC_MODE_MASK;
1209         irq.dest_mode = icr_low & APIC_DEST_MASK;
1210         irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1211         irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1212         irq.shorthand = icr_low & APIC_SHORT_MASK;
1213         irq.msi_redir_hint = false;
1214         if (apic_x2apic_mode(apic))
1215                 irq.dest_id = icr_high;
1216         else
1217                 irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1218
1219         trace_kvm_apic_ipi(icr_low, irq.dest_id);
1220
1221         kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1222 }
1223
1224 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1225 {
1226         ktime_t remaining, now;
1227         s64 ns;
1228         u32 tmcct;
1229
1230         ASSERT(apic != NULL);
1231
1232         /* if initial count is 0, current count should also be 0 */
1233         if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1234                 apic->lapic_timer.period == 0)
1235                 return 0;
1236
1237         now = ktime_get();
1238         remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1239         if (ktime_to_ns(remaining) < 0)
1240                 remaining = 0;
1241
1242         ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1243         tmcct = div64_u64(ns,
1244                          (APIC_BUS_CYCLE_NS * apic->divide_count));
1245
1246         return tmcct;
1247 }
1248
1249 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1250 {
1251         struct kvm_vcpu *vcpu = apic->vcpu;
1252         struct kvm_run *run = vcpu->run;
1253
1254         kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1255         run->tpr_access.rip = kvm_rip_read(vcpu);
1256         run->tpr_access.is_write = write;
1257 }
1258
1259 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1260 {
1261         if (apic->vcpu->arch.tpr_access_reporting)
1262                 __report_tpr_access(apic, write);
1263 }
1264
1265 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1266 {
1267         u32 val = 0;
1268
1269         if (offset >= LAPIC_MMIO_LENGTH)
1270                 return 0;
1271
1272         switch (offset) {
1273         case APIC_ARBPRI:
1274                 break;
1275
1276         case APIC_TMCCT:        /* Timer CCR */
1277                 if (apic_lvtt_tscdeadline(apic))
1278                         return 0;
1279
1280                 val = apic_get_tmcct(apic);
1281                 break;
1282         case APIC_PROCPRI:
1283                 apic_update_ppr(apic);
1284                 val = kvm_lapic_get_reg(apic, offset);
1285                 break;
1286         case APIC_TASKPRI:
1287                 report_tpr_access(apic, false);
1288                 /* fall thru */
1289         default:
1290                 val = kvm_lapic_get_reg(apic, offset);
1291                 break;
1292         }
1293
1294         return val;
1295 }
1296
1297 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1298 {
1299         return container_of(dev, struct kvm_lapic, dev);
1300 }
1301
1302 #define APIC_REG_MASK(reg)      (1ull << ((reg) >> 4))
1303 #define APIC_REGS_MASK(first, count) \
1304         (APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1305
1306 int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1307                 void *data)
1308 {
1309         unsigned char alignment = offset & 0xf;
1310         u32 result;
1311         /* this bitmask has a bit cleared for each reserved register */
1312         u64 valid_reg_mask =
1313                 APIC_REG_MASK(APIC_ID) |
1314                 APIC_REG_MASK(APIC_LVR) |
1315                 APIC_REG_MASK(APIC_TASKPRI) |
1316                 APIC_REG_MASK(APIC_PROCPRI) |
1317                 APIC_REG_MASK(APIC_LDR) |
1318                 APIC_REG_MASK(APIC_DFR) |
1319                 APIC_REG_MASK(APIC_SPIV) |
1320                 APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1321                 APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1322                 APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1323                 APIC_REG_MASK(APIC_ESR) |
1324                 APIC_REG_MASK(APIC_ICR) |
1325                 APIC_REG_MASK(APIC_ICR2) |
1326                 APIC_REG_MASK(APIC_LVTT) |
1327                 APIC_REG_MASK(APIC_LVTTHMR) |
1328                 APIC_REG_MASK(APIC_LVTPC) |
1329                 APIC_REG_MASK(APIC_LVT0) |
1330                 APIC_REG_MASK(APIC_LVT1) |
1331                 APIC_REG_MASK(APIC_LVTERR) |
1332                 APIC_REG_MASK(APIC_TMICT) |
1333                 APIC_REG_MASK(APIC_TMCCT) |
1334                 APIC_REG_MASK(APIC_TDCR);
1335
1336         /* ARBPRI is not valid on x2APIC */
1337         if (!apic_x2apic_mode(apic))
1338                 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI);
1339
1340         if (alignment + len > 4)
1341                 return 1;
1342
1343         if (offset > 0x3f0 || !(valid_reg_mask & APIC_REG_MASK(offset)))
1344                 return 1;
1345
1346         result = __apic_read(apic, offset & ~0xf);
1347
1348         trace_kvm_apic_read(offset, result);
1349
1350         switch (len) {
1351         case 1:
1352         case 2:
1353         case 4:
1354                 memcpy(data, (char *)&result + alignment, len);
1355                 break;
1356         default:
1357                 printk(KERN_ERR "Local APIC read with len = %x, "
1358                        "should be 1,2, or 4 instead\n", len);
1359                 break;
1360         }
1361         return 0;
1362 }
1363 EXPORT_SYMBOL_GPL(kvm_lapic_reg_read);
1364
1365 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1366 {
1367         return addr >= apic->base_address &&
1368                 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1369 }
1370
1371 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1372                            gpa_t address, int len, void *data)
1373 {
1374         struct kvm_lapic *apic = to_lapic(this);
1375         u32 offset = address - apic->base_address;
1376
1377         if (!apic_mmio_in_range(apic, address))
1378                 return -EOPNOTSUPP;
1379
1380         if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1381                 if (!kvm_check_has_quirk(vcpu->kvm,
1382                                          KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1383                         return -EOPNOTSUPP;
1384
1385                 memset(data, 0xff, len);
1386                 return 0;
1387         }
1388
1389         kvm_lapic_reg_read(apic, offset, len, data);
1390
1391         return 0;
1392 }
1393
1394 static void update_divide_count(struct kvm_lapic *apic)
1395 {
1396         u32 tmp1, tmp2, tdcr;
1397
1398         tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1399         tmp1 = tdcr & 0xf;
1400         tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1401         apic->divide_count = 0x1 << (tmp2 & 0x7);
1402 }
1403
1404 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1405 {
1406         /*
1407          * Do not allow the guest to program periodic timers with small
1408          * interval, since the hrtimers are not throttled by the host
1409          * scheduler.
1410          */
1411         if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1412                 s64 min_period = min_timer_period_us * 1000LL;
1413
1414                 if (apic->lapic_timer.period < min_period) {
1415                         pr_info_ratelimited(
1416                             "kvm: vcpu %i: requested %lld ns "
1417                             "lapic timer period limited to %lld ns\n",
1418                             apic->vcpu->vcpu_id,
1419                             apic->lapic_timer.period, min_period);
1420                         apic->lapic_timer.period = min_period;
1421                 }
1422         }
1423 }
1424
1425 static void apic_update_lvtt(struct kvm_lapic *apic)
1426 {
1427         u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1428                         apic->lapic_timer.timer_mode_mask;
1429
1430         if (apic->lapic_timer.timer_mode != timer_mode) {
1431                 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1432                                 APIC_LVT_TIMER_TSCDEADLINE)) {
1433                         hrtimer_cancel(&apic->lapic_timer.timer);
1434                         kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1435                         apic->lapic_timer.period = 0;
1436                         apic->lapic_timer.tscdeadline = 0;
1437                 }
1438                 apic->lapic_timer.timer_mode = timer_mode;
1439                 limit_periodic_timer_frequency(apic);
1440         }
1441 }
1442
1443 /*
1444  * On APICv, this test will cause a busy wait
1445  * during a higher-priority task.
1446  */
1447
1448 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1449 {
1450         struct kvm_lapic *apic = vcpu->arch.apic;
1451         u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1452
1453         if (kvm_apic_hw_enabled(apic)) {
1454                 int vec = reg & APIC_VECTOR_MASK;
1455                 void *bitmap = apic->regs + APIC_ISR;
1456
1457                 if (vcpu->arch.apicv_active)
1458                         bitmap = apic->regs + APIC_IRR;
1459
1460                 if (apic_test_vector(vec, bitmap))
1461                         return true;
1462         }
1463         return false;
1464 }
1465
1466 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1467 {
1468         u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1469
1470         /*
1471          * If the guest TSC is running at a different ratio than the host, then
1472          * convert the delay to nanoseconds to achieve an accurate delay.  Note
1473          * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1474          * always for VMX enabled hardware.
1475          */
1476         if (vcpu->arch.tsc_scaling_ratio == kvm_default_tsc_scaling_ratio) {
1477                 __delay(min(guest_cycles,
1478                         nsec_to_cycles(vcpu, timer_advance_ns)));
1479         } else {
1480                 u64 delay_ns = guest_cycles * 1000000ULL;
1481                 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1482                 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1483         }
1484 }
1485
1486 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1487                                               s64 advance_expire_delta)
1488 {
1489         struct kvm_lapic *apic = vcpu->arch.apic;
1490         u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1491         u64 ns;
1492
1493         /* Do not adjust for tiny fluctuations or large random spikes. */
1494         if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1495             abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1496                 return;
1497
1498         /* too early */
1499         if (advance_expire_delta < 0) {
1500                 ns = -advance_expire_delta * 1000000ULL;
1501                 do_div(ns, vcpu->arch.virtual_tsc_khz);
1502                 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1503         } else {
1504         /* too late */
1505                 ns = advance_expire_delta * 1000000ULL;
1506                 do_div(ns, vcpu->arch.virtual_tsc_khz);
1507                 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1508         }
1509
1510         if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1511                 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1512         apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1513 }
1514
1515 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1516 {
1517         struct kvm_lapic *apic = vcpu->arch.apic;
1518         u64 guest_tsc, tsc_deadline;
1519
1520         if (apic->lapic_timer.expired_tscdeadline == 0)
1521                 return;
1522
1523         tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1524         apic->lapic_timer.expired_tscdeadline = 0;
1525         guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1526         apic->lapic_timer.advance_expire_delta = guest_tsc - tsc_deadline;
1527
1528         if (guest_tsc < tsc_deadline)
1529                 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1530
1531         if (lapic_timer_advance_dynamic)
1532                 adjust_lapic_timer_advance(vcpu, apic->lapic_timer.advance_expire_delta);
1533 }
1534
1535 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1536 {
1537         if (lapic_timer_int_injected(vcpu))
1538                 __kvm_wait_lapic_expire(vcpu);
1539 }
1540 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1541
1542 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1543 {
1544         struct kvm_timer *ktimer = &apic->lapic_timer;
1545
1546         kvm_apic_local_deliver(apic, APIC_LVTT);
1547         if (apic_lvtt_tscdeadline(apic))
1548                 ktimer->tscdeadline = 0;
1549         if (apic_lvtt_oneshot(apic)) {
1550                 ktimer->tscdeadline = 0;
1551                 ktimer->target_expiration = 0;
1552         }
1553 }
1554
1555 static void apic_timer_expired(struct kvm_lapic *apic)
1556 {
1557         struct kvm_vcpu *vcpu = apic->vcpu;
1558         struct kvm_timer *ktimer = &apic->lapic_timer;
1559
1560         if (atomic_read(&apic->lapic_timer.pending))
1561                 return;
1562
1563         if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1564                 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1565
1566         if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1567                 if (apic->lapic_timer.timer_advance_ns)
1568                         __kvm_wait_lapic_expire(vcpu);
1569                 kvm_apic_inject_pending_timer_irqs(apic);
1570                 return;
1571         }
1572
1573         atomic_inc(&apic->lapic_timer.pending);
1574         kvm_set_pending_timer(vcpu);
1575 }
1576
1577 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1578 {
1579         struct kvm_timer *ktimer = &apic->lapic_timer;
1580         u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1581         u64 ns = 0;
1582         ktime_t expire;
1583         struct kvm_vcpu *vcpu = apic->vcpu;
1584         unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1585         unsigned long flags;
1586         ktime_t now;
1587
1588         if (unlikely(!tscdeadline || !this_tsc_khz))
1589                 return;
1590
1591         local_irq_save(flags);
1592
1593         now = ktime_get();
1594         guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1595
1596         ns = (tscdeadline - guest_tsc) * 1000000ULL;
1597         do_div(ns, this_tsc_khz);
1598
1599         if (likely(tscdeadline > guest_tsc) &&
1600             likely(ns > apic->lapic_timer.timer_advance_ns)) {
1601                 expire = ktime_add_ns(now, ns);
1602                 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1603                 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1604         } else
1605                 apic_timer_expired(apic);
1606
1607         local_irq_restore(flags);
1608 }
1609
1610 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1611 {
1612         ktime_t now, remaining;
1613         u64 ns_remaining_old, ns_remaining_new;
1614
1615         apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1616                 * APIC_BUS_CYCLE_NS * apic->divide_count;
1617         limit_periodic_timer_frequency(apic);
1618
1619         now = ktime_get();
1620         remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1621         if (ktime_to_ns(remaining) < 0)
1622                 remaining = 0;
1623
1624         ns_remaining_old = ktime_to_ns(remaining);
1625         ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1626                                            apic->divide_count, old_divisor);
1627
1628         apic->lapic_timer.tscdeadline +=
1629                 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1630                 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1631         apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1632 }
1633
1634 static bool set_target_expiration(struct kvm_lapic *apic)
1635 {
1636         ktime_t now;
1637         u64 tscl = rdtsc();
1638
1639         now = ktime_get();
1640         apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1641                 * APIC_BUS_CYCLE_NS * apic->divide_count;
1642
1643         if (!apic->lapic_timer.period) {
1644                 apic->lapic_timer.tscdeadline = 0;
1645                 return false;
1646         }
1647
1648         limit_periodic_timer_frequency(apic);
1649
1650         apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1651                 nsec_to_cycles(apic->vcpu, apic->lapic_timer.period);
1652         apic->lapic_timer.target_expiration = ktime_add_ns(now, apic->lapic_timer.period);
1653
1654         return true;
1655 }
1656
1657 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1658 {
1659         ktime_t now = ktime_get();
1660         u64 tscl = rdtsc();
1661         ktime_t delta;
1662
1663         /*
1664          * Synchronize both deadlines to the same time source or
1665          * differences in the periods (caused by differences in the
1666          * underlying clocks or numerical approximation errors) will
1667          * cause the two to drift apart over time as the errors
1668          * accumulate.
1669          */
1670         apic->lapic_timer.target_expiration =
1671                 ktime_add_ns(apic->lapic_timer.target_expiration,
1672                                 apic->lapic_timer.period);
1673         delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1674         apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1675                 nsec_to_cycles(apic->vcpu, delta);
1676 }
1677
1678 static void start_sw_period(struct kvm_lapic *apic)
1679 {
1680         if (!apic->lapic_timer.period)
1681                 return;
1682
1683         if (ktime_after(ktime_get(),
1684                         apic->lapic_timer.target_expiration)) {
1685                 apic_timer_expired(apic);
1686
1687                 if (apic_lvtt_oneshot(apic))
1688                         return;
1689
1690                 advance_periodic_target_expiration(apic);
1691         }
1692
1693         hrtimer_start(&apic->lapic_timer.timer,
1694                 apic->lapic_timer.target_expiration,
1695                 HRTIMER_MODE_ABS_HARD);
1696 }
1697
1698 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1699 {
1700         if (!lapic_in_kernel(vcpu))
1701                 return false;
1702
1703         return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1704 }
1705 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1706
1707 static void cancel_hv_timer(struct kvm_lapic *apic)
1708 {
1709         WARN_ON(preemptible());
1710         WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1711         kvm_x86_ops->cancel_hv_timer(apic->vcpu);
1712         apic->lapic_timer.hv_timer_in_use = false;
1713 }
1714
1715 static bool start_hv_timer(struct kvm_lapic *apic)
1716 {
1717         struct kvm_timer *ktimer = &apic->lapic_timer;
1718         struct kvm_vcpu *vcpu = apic->vcpu;
1719         bool expired;
1720
1721         WARN_ON(preemptible());
1722         if (!kvm_x86_ops->set_hv_timer)
1723                 return false;
1724
1725         if (!ktimer->tscdeadline)
1726                 return false;
1727
1728         if (kvm_x86_ops->set_hv_timer(vcpu, ktimer->tscdeadline, &expired))
1729                 return false;
1730
1731         ktimer->hv_timer_in_use = true;
1732         hrtimer_cancel(&ktimer->timer);
1733
1734         /*
1735          * To simplify handling the periodic timer, leave the hv timer running
1736          * even if the deadline timer has expired, i.e. rely on the resulting
1737          * VM-Exit to recompute the periodic timer's target expiration.
1738          */
1739         if (!apic_lvtt_period(apic)) {
1740                 /*
1741                  * Cancel the hv timer if the sw timer fired while the hv timer
1742                  * was being programmed, or if the hv timer itself expired.
1743                  */
1744                 if (atomic_read(&ktimer->pending)) {
1745                         cancel_hv_timer(apic);
1746                 } else if (expired) {
1747                         apic_timer_expired(apic);
1748                         cancel_hv_timer(apic);
1749                 }
1750         }
1751
1752         trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
1753
1754         return true;
1755 }
1756
1757 static void start_sw_timer(struct kvm_lapic *apic)
1758 {
1759         struct kvm_timer *ktimer = &apic->lapic_timer;
1760
1761         WARN_ON(preemptible());
1762         if (apic->lapic_timer.hv_timer_in_use)
1763                 cancel_hv_timer(apic);
1764         if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1765                 return;
1766
1767         if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1768                 start_sw_period(apic);
1769         else if (apic_lvtt_tscdeadline(apic))
1770                 start_sw_tscdeadline(apic);
1771         trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1772 }
1773
1774 static void restart_apic_timer(struct kvm_lapic *apic)
1775 {
1776         preempt_disable();
1777
1778         if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
1779                 goto out;
1780
1781         if (!start_hv_timer(apic))
1782                 start_sw_timer(apic);
1783 out:
1784         preempt_enable();
1785 }
1786
1787 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1788 {
1789         struct kvm_lapic *apic = vcpu->arch.apic;
1790
1791         preempt_disable();
1792         /* If the preempt notifier has already run, it also called apic_timer_expired */
1793         if (!apic->lapic_timer.hv_timer_in_use)
1794                 goto out;
1795         WARN_ON(swait_active(&vcpu->wq));
1796         cancel_hv_timer(apic);
1797         apic_timer_expired(apic);
1798
1799         if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1800                 advance_periodic_target_expiration(apic);
1801                 restart_apic_timer(apic);
1802         }
1803 out:
1804         preempt_enable();
1805 }
1806 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1807
1808 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1809 {
1810         restart_apic_timer(vcpu->arch.apic);
1811 }
1812 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_hv_timer);
1813
1814 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1815 {
1816         struct kvm_lapic *apic = vcpu->arch.apic;
1817
1818         preempt_disable();
1819         /* Possibly the TSC deadline timer is not enabled yet */
1820         if (apic->lapic_timer.hv_timer_in_use)
1821                 start_sw_timer(apic);
1822         preempt_enable();
1823 }
1824 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_sw_timer);
1825
1826 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
1827 {
1828         struct kvm_lapic *apic = vcpu->arch.apic;
1829
1830         WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1831         restart_apic_timer(apic);
1832 }
1833
1834 static void start_apic_timer(struct kvm_lapic *apic)
1835 {
1836         atomic_set(&apic->lapic_timer.pending, 0);
1837
1838         if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1839             && !set_target_expiration(apic))
1840                 return;
1841
1842         restart_apic_timer(apic);
1843 }
1844
1845 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
1846 {
1847         bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
1848
1849         if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
1850                 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
1851                 if (lvt0_in_nmi_mode) {
1852                         atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1853                 } else
1854                         atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1855         }
1856 }
1857
1858 int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
1859 {
1860         int ret = 0;
1861
1862         trace_kvm_apic_write(reg, val);
1863
1864         switch (reg) {
1865         case APIC_ID:           /* Local APIC ID */
1866                 if (!apic_x2apic_mode(apic))
1867                         kvm_apic_set_xapic_id(apic, val >> 24);
1868                 else
1869                         ret = 1;
1870                 break;
1871
1872         case APIC_TASKPRI:
1873                 report_tpr_access(apic, true);
1874                 apic_set_tpr(apic, val & 0xff);
1875                 break;
1876
1877         case APIC_EOI:
1878                 apic_set_eoi(apic);
1879                 break;
1880
1881         case APIC_LDR:
1882                 if (!apic_x2apic_mode(apic))
1883                         kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
1884                 else
1885                         ret = 1;
1886                 break;
1887
1888         case APIC_DFR:
1889                 if (!apic_x2apic_mode(apic)) {
1890                         kvm_lapic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
1891                         recalculate_apic_map(apic->vcpu->kvm);
1892                 } else
1893                         ret = 1;
1894                 break;
1895
1896         case APIC_SPIV: {
1897                 u32 mask = 0x3ff;
1898                 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
1899                         mask |= APIC_SPIV_DIRECTED_EOI;
1900                 apic_set_spiv(apic, val & mask);
1901                 if (!(val & APIC_SPIV_APIC_ENABLED)) {
1902                         int i;
1903                         u32 lvt_val;
1904
1905                         for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
1906                                 lvt_val = kvm_lapic_get_reg(apic,
1907                                                        APIC_LVTT + 0x10 * i);
1908                                 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
1909                                              lvt_val | APIC_LVT_MASKED);
1910                         }
1911                         apic_update_lvtt(apic);
1912                         atomic_set(&apic->lapic_timer.pending, 0);
1913
1914                 }
1915                 break;
1916         }
1917         case APIC_ICR:
1918                 /* No delay here, so we always clear the pending bit */
1919                 val &= ~(1 << 12);
1920                 apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
1921                 kvm_lapic_set_reg(apic, APIC_ICR, val);
1922                 break;
1923
1924         case APIC_ICR2:
1925                 if (!apic_x2apic_mode(apic))
1926                         val &= 0xff000000;
1927                 kvm_lapic_set_reg(apic, APIC_ICR2, val);
1928                 break;
1929
1930         case APIC_LVT0:
1931                 apic_manage_nmi_watchdog(apic, val);
1932                 /* fall through */
1933         case APIC_LVTTHMR:
1934         case APIC_LVTPC:
1935         case APIC_LVT1:
1936         case APIC_LVTERR: {
1937                 /* TODO: Check vector */
1938                 size_t size;
1939                 u32 index;
1940
1941                 if (!kvm_apic_sw_enabled(apic))
1942                         val |= APIC_LVT_MASKED;
1943                 size = ARRAY_SIZE(apic_lvt_mask);
1944                 index = array_index_nospec(
1945                                 (reg - APIC_LVTT) >> 4, size);
1946                 val &= apic_lvt_mask[index];
1947                 kvm_lapic_set_reg(apic, reg, val);
1948                 break;
1949         }
1950
1951         case APIC_LVTT:
1952                 if (!kvm_apic_sw_enabled(apic))
1953                         val |= APIC_LVT_MASKED;
1954                 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
1955                 kvm_lapic_set_reg(apic, APIC_LVTT, val);
1956                 apic_update_lvtt(apic);
1957                 break;
1958
1959         case APIC_TMICT:
1960                 if (apic_lvtt_tscdeadline(apic))
1961                         break;
1962
1963                 hrtimer_cancel(&apic->lapic_timer.timer);
1964                 kvm_lapic_set_reg(apic, APIC_TMICT, val);
1965                 start_apic_timer(apic);
1966                 break;
1967
1968         case APIC_TDCR: {
1969                 uint32_t old_divisor = apic->divide_count;
1970
1971                 kvm_lapic_set_reg(apic, APIC_TDCR, val);
1972                 update_divide_count(apic);
1973                 if (apic->divide_count != old_divisor &&
1974                                 apic->lapic_timer.period) {
1975                         hrtimer_cancel(&apic->lapic_timer.timer);
1976                         update_target_expiration(apic, old_divisor);
1977                         restart_apic_timer(apic);
1978                 }
1979                 break;
1980         }
1981         case APIC_ESR:
1982                 if (apic_x2apic_mode(apic) && val != 0)
1983                         ret = 1;
1984                 break;
1985
1986         case APIC_SELF_IPI:
1987                 if (apic_x2apic_mode(apic)) {
1988                         kvm_lapic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
1989                 } else
1990                         ret = 1;
1991                 break;
1992         default:
1993                 ret = 1;
1994                 break;
1995         }
1996
1997         return ret;
1998 }
1999 EXPORT_SYMBOL_GPL(kvm_lapic_reg_write);
2000
2001 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2002                             gpa_t address, int len, const void *data)
2003 {
2004         struct kvm_lapic *apic = to_lapic(this);
2005         unsigned int offset = address - apic->base_address;
2006         u32 val;
2007
2008         if (!apic_mmio_in_range(apic, address))
2009                 return -EOPNOTSUPP;
2010
2011         if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2012                 if (!kvm_check_has_quirk(vcpu->kvm,
2013                                          KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2014                         return -EOPNOTSUPP;
2015
2016                 return 0;
2017         }
2018
2019         /*
2020          * APIC register must be aligned on 128-bits boundary.
2021          * 32/64/128 bits registers must be accessed thru 32 bits.
2022          * Refer SDM 8.4.1
2023          */
2024         if (len != 4 || (offset & 0xf))
2025                 return 0;
2026
2027         val = *(u32*)data;
2028
2029         kvm_lapic_reg_write(apic, offset & 0xff0, val);
2030
2031         return 0;
2032 }
2033
2034 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2035 {
2036         kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2037 }
2038 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2039
2040 /* emulate APIC access in a trap manner */
2041 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2042 {
2043         u32 val = 0;
2044
2045         /* hw has done the conditional check and inst decode */
2046         offset &= 0xff0;
2047
2048         kvm_lapic_reg_read(vcpu->arch.apic, offset, 4, &val);
2049
2050         /* TODO: optimize to just emulate side effect w/o one more write */
2051         kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
2052 }
2053 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2054
2055 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2056 {
2057         struct kvm_lapic *apic = vcpu->arch.apic;
2058
2059         if (!vcpu->arch.apic)
2060                 return;
2061
2062         hrtimer_cancel(&apic->lapic_timer.timer);
2063
2064         if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2065                 static_key_slow_dec_deferred(&apic_hw_disabled);
2066
2067         if (!apic->sw_enabled)
2068                 static_key_slow_dec_deferred(&apic_sw_disabled);
2069
2070         if (apic->regs)
2071                 free_page((unsigned long)apic->regs);
2072
2073         kfree(apic);
2074 }
2075
2076 /*
2077  *----------------------------------------------------------------------
2078  * LAPIC interface
2079  *----------------------------------------------------------------------
2080  */
2081 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2082 {
2083         struct kvm_lapic *apic = vcpu->arch.apic;
2084
2085         if (!lapic_in_kernel(vcpu) ||
2086                 !apic_lvtt_tscdeadline(apic))
2087                 return 0;
2088
2089         return apic->lapic_timer.tscdeadline;
2090 }
2091
2092 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2093 {
2094         struct kvm_lapic *apic = vcpu->arch.apic;
2095
2096         if (!kvm_apic_present(vcpu) || apic_lvtt_oneshot(apic) ||
2097                         apic_lvtt_period(apic))
2098                 return;
2099
2100         hrtimer_cancel(&apic->lapic_timer.timer);
2101         apic->lapic_timer.tscdeadline = data;
2102         start_apic_timer(apic);
2103 }
2104
2105 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2106 {
2107         apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2108 }
2109
2110 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2111 {
2112         u64 tpr;
2113
2114         tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2115
2116         return (tpr & 0xf0) >> 4;
2117 }
2118
2119 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2120 {
2121         u64 old_value = vcpu->arch.apic_base;
2122         struct kvm_lapic *apic = vcpu->arch.apic;
2123
2124         if (!apic)
2125                 value |= MSR_IA32_APICBASE_BSP;
2126
2127         vcpu->arch.apic_base = value;
2128
2129         if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2130                 kvm_update_cpuid(vcpu);
2131
2132         if (!apic)
2133                 return;
2134
2135         /* update jump label if enable bit changes */
2136         if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2137                 if (value & MSR_IA32_APICBASE_ENABLE) {
2138                         kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2139                         static_key_slow_dec_deferred(&apic_hw_disabled);
2140                 } else {
2141                         static_key_slow_inc(&apic_hw_disabled.key);
2142                         recalculate_apic_map(vcpu->kvm);
2143                 }
2144         }
2145
2146         if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
2147                 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2148
2149         if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE))
2150                 kvm_x86_ops->set_virtual_apic_mode(vcpu);
2151
2152         apic->base_address = apic->vcpu->arch.apic_base &
2153                              MSR_IA32_APICBASE_BASE;
2154
2155         if ((value & MSR_IA32_APICBASE_ENABLE) &&
2156              apic->base_address != APIC_DEFAULT_PHYS_BASE)
2157                 pr_warn_once("APIC base relocation is unsupported by KVM");
2158 }
2159
2160 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2161 {
2162         struct kvm_lapic *apic = vcpu->arch.apic;
2163         int i;
2164
2165         if (!apic)
2166                 return;
2167
2168         /* Stop the timer in case it's a reset to an active apic */
2169         hrtimer_cancel(&apic->lapic_timer.timer);
2170
2171         if (!init_event) {
2172                 kvm_lapic_set_base(vcpu, APIC_DEFAULT_PHYS_BASE |
2173                                          MSR_IA32_APICBASE_ENABLE);
2174                 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2175         }
2176         kvm_apic_set_version(apic->vcpu);
2177
2178         for (i = 0; i < KVM_APIC_LVT_NUM; i++)
2179                 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
2180         apic_update_lvtt(apic);
2181         if (kvm_vcpu_is_reset_bsp(vcpu) &&
2182             kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2183                 kvm_lapic_set_reg(apic, APIC_LVT0,
2184                              SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2185         apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2186
2187         kvm_lapic_set_reg(apic, APIC_DFR, 0xffffffffU);
2188         apic_set_spiv(apic, 0xff);
2189         kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2190         if (!apic_x2apic_mode(apic))
2191                 kvm_apic_set_ldr(apic, 0);
2192         kvm_lapic_set_reg(apic, APIC_ESR, 0);
2193         kvm_lapic_set_reg(apic, APIC_ICR, 0);
2194         kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2195         kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2196         kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2197         for (i = 0; i < 8; i++) {
2198                 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2199                 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2200                 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2201         }
2202         apic->irr_pending = vcpu->arch.apicv_active;
2203         apic->isr_count = vcpu->arch.apicv_active ? 1 : 0;
2204         apic->highest_isr_cache = -1;
2205         update_divide_count(apic);
2206         atomic_set(&apic->lapic_timer.pending, 0);
2207         if (kvm_vcpu_is_bsp(vcpu))
2208                 kvm_lapic_set_base(vcpu,
2209                                 vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
2210         vcpu->arch.pv_eoi.msr_val = 0;
2211         apic_update_ppr(apic);
2212         if (vcpu->arch.apicv_active) {
2213                 kvm_x86_ops->apicv_post_state_restore(vcpu);
2214                 kvm_x86_ops->hwapic_irr_update(vcpu, -1);
2215                 kvm_x86_ops->hwapic_isr_update(vcpu, -1);
2216         }
2217
2218         vcpu->arch.apic_arb_prio = 0;
2219         vcpu->arch.apic_attention = 0;
2220 }
2221
2222 /*
2223  *----------------------------------------------------------------------
2224  * timer interface
2225  *----------------------------------------------------------------------
2226  */
2227
2228 static bool lapic_is_periodic(struct kvm_lapic *apic)
2229 {
2230         return apic_lvtt_period(apic);
2231 }
2232
2233 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2234 {
2235         struct kvm_lapic *apic = vcpu->arch.apic;
2236
2237         if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2238                 return atomic_read(&apic->lapic_timer.pending);
2239
2240         return 0;
2241 }
2242
2243 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2244 {
2245         u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2246         int vector, mode, trig_mode;
2247         int r;
2248
2249         if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2250                 vector = reg & APIC_VECTOR_MASK;
2251                 mode = reg & APIC_MODE_MASK;
2252                 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2253
2254                 r = __apic_accept_irq(apic, mode, vector, 1, trig_mode, NULL);
2255                 if (r && lvt_type == APIC_LVTPC)
2256                         kvm_lapic_set_reg(apic, APIC_LVTPC, reg | APIC_LVT_MASKED);
2257                 return r;
2258         }
2259         return 0;
2260 }
2261
2262 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2263 {
2264         struct kvm_lapic *apic = vcpu->arch.apic;
2265
2266         if (apic)
2267                 kvm_apic_local_deliver(apic, APIC_LVT0);
2268 }
2269
2270 static const struct kvm_io_device_ops apic_mmio_ops = {
2271         .read     = apic_mmio_read,
2272         .write    = apic_mmio_write,
2273 };
2274
2275 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2276 {
2277         struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2278         struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2279
2280         apic_timer_expired(apic);
2281
2282         if (lapic_is_periodic(apic)) {
2283                 advance_periodic_target_expiration(apic);
2284                 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2285                 return HRTIMER_RESTART;
2286         } else
2287                 return HRTIMER_NORESTART;
2288 }
2289
2290 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2291 {
2292         struct kvm_lapic *apic;
2293
2294         ASSERT(vcpu != NULL);
2295
2296         apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2297         if (!apic)
2298                 goto nomem;
2299
2300         vcpu->arch.apic = apic;
2301
2302         apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2303         if (!apic->regs) {
2304                 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2305                        vcpu->vcpu_id);
2306                 goto nomem_free_apic;
2307         }
2308         apic->vcpu = vcpu;
2309
2310         hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2311                      HRTIMER_MODE_ABS_HARD);
2312         apic->lapic_timer.timer.function = apic_timer_fn;
2313         if (timer_advance_ns == -1) {
2314                 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2315                 lapic_timer_advance_dynamic = true;
2316         } else {
2317                 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2318                 lapic_timer_advance_dynamic = false;
2319         }
2320
2321         /*
2322          * APIC is created enabled. This will prevent kvm_lapic_set_base from
2323          * thinking that APIC state has changed.
2324          */
2325         vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2326         static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2327         kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2328
2329         return 0;
2330 nomem_free_apic:
2331         kfree(apic);
2332         vcpu->arch.apic = NULL;
2333 nomem:
2334         return -ENOMEM;
2335 }
2336
2337 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2338 {
2339         struct kvm_lapic *apic = vcpu->arch.apic;
2340         u32 ppr;
2341
2342         if (!kvm_apic_present(vcpu))
2343                 return -1;
2344
2345         __apic_update_ppr(apic, &ppr);
2346         return apic_has_interrupt_for_ppr(apic, ppr);
2347 }
2348
2349 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2350 {
2351         u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2352         int r = 0;
2353
2354         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2355                 r = 1;
2356         if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2357             GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2358                 r = 1;
2359         return r;
2360 }
2361
2362 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2363 {
2364         struct kvm_lapic *apic = vcpu->arch.apic;
2365
2366         if (atomic_read(&apic->lapic_timer.pending) > 0) {
2367                 kvm_apic_inject_pending_timer_irqs(apic);
2368                 atomic_set(&apic->lapic_timer.pending, 0);
2369         }
2370 }
2371
2372 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2373 {
2374         int vector = kvm_apic_has_interrupt(vcpu);
2375         struct kvm_lapic *apic = vcpu->arch.apic;
2376         u32 ppr;
2377
2378         if (vector == -1)
2379                 return -1;
2380
2381         /*
2382          * We get here even with APIC virtualization enabled, if doing
2383          * nested virtualization and L1 runs with the "acknowledge interrupt
2384          * on exit" mode.  Then we cannot inject the interrupt via RVI,
2385          * because the process would deliver it through the IDT.
2386          */
2387
2388         apic_clear_irr(vector, apic);
2389         if (test_bit(vector, vcpu_to_synic(vcpu)->auto_eoi_bitmap)) {
2390                 /*
2391                  * For auto-EOI interrupts, there might be another pending
2392                  * interrupt above PPR, so check whether to raise another
2393                  * KVM_REQ_EVENT.
2394                  */
2395                 apic_update_ppr(apic);
2396         } else {
2397                 /*
2398                  * For normal interrupts, PPR has been raised and there cannot
2399                  * be a higher-priority pending interrupt---except if there was
2400                  * a concurrent interrupt injection, but that would have
2401                  * triggered KVM_REQ_EVENT already.
2402                  */
2403                 apic_set_isr(vector, apic);
2404                 __apic_update_ppr(apic, &ppr);
2405         }
2406
2407         return vector;
2408 }
2409
2410 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2411                 struct kvm_lapic_state *s, bool set)
2412 {
2413         if (apic_x2apic_mode(vcpu->arch.apic)) {
2414                 u32 *id = (u32 *)(s->regs + APIC_ID);
2415                 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2416
2417                 if (vcpu->kvm->arch.x2apic_format) {
2418                         if (*id != vcpu->vcpu_id)
2419                                 return -EINVAL;
2420                 } else {
2421                         if (set)
2422                                 *id >>= 24;
2423                         else
2424                                 *id <<= 24;
2425                 }
2426
2427                 /* In x2APIC mode, the LDR is fixed and based on the id */
2428                 if (set)
2429                         *ldr = kvm_apic_calc_x2apic_ldr(*id);
2430         }
2431
2432         return 0;
2433 }
2434
2435 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2436 {
2437         memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2438         return kvm_apic_state_fixup(vcpu, s, false);
2439 }
2440
2441 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2442 {
2443         struct kvm_lapic *apic = vcpu->arch.apic;
2444         int r;
2445
2446
2447         kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2448         /* set SPIV separately to get count of SW disabled APICs right */
2449         apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2450
2451         r = kvm_apic_state_fixup(vcpu, s, true);
2452         if (r)
2453                 return r;
2454         memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2455
2456         recalculate_apic_map(vcpu->kvm);
2457         kvm_apic_set_version(vcpu);
2458
2459         apic_update_ppr(apic);
2460         hrtimer_cancel(&apic->lapic_timer.timer);
2461         apic_update_lvtt(apic);
2462         apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2463         update_divide_count(apic);
2464         start_apic_timer(apic);
2465         apic->irr_pending = true;
2466         apic->isr_count = vcpu->arch.apicv_active ?
2467                                 1 : count_vectors(apic->regs + APIC_ISR);
2468         apic->highest_isr_cache = -1;
2469         if (vcpu->arch.apicv_active) {
2470                 kvm_x86_ops->apicv_post_state_restore(vcpu);
2471                 kvm_x86_ops->hwapic_irr_update(vcpu,
2472                                 apic_find_highest_irr(apic));
2473                 kvm_x86_ops->hwapic_isr_update(vcpu,
2474                                 apic_find_highest_isr(apic));
2475         }
2476         kvm_make_request(KVM_REQ_EVENT, vcpu);
2477         if (ioapic_in_kernel(vcpu->kvm))
2478                 kvm_rtc_eoi_tracking_restore_one(vcpu);
2479
2480         vcpu->arch.apic_arb_prio = 0;
2481
2482         return 0;
2483 }
2484
2485 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2486 {
2487         struct hrtimer *timer;
2488
2489         if (!lapic_in_kernel(vcpu) ||
2490                 kvm_can_post_timer_interrupt(vcpu))
2491                 return;
2492
2493         timer = &vcpu->arch.apic->lapic_timer.timer;
2494         if (hrtimer_cancel(timer))
2495                 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2496 }
2497
2498 /*
2499  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2500  *
2501  * Detect whether guest triggered PV EOI since the
2502  * last entry. If yes, set EOI on guests's behalf.
2503  * Clear PV EOI in guest memory in any case.
2504  */
2505 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2506                                         struct kvm_lapic *apic)
2507 {
2508         bool pending;
2509         int vector;
2510         /*
2511          * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2512          * and KVM_PV_EOI_ENABLED in guest memory as follows:
2513          *
2514          * KVM_APIC_PV_EOI_PENDING is unset:
2515          *      -> host disabled PV EOI.
2516          * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2517          *      -> host enabled PV EOI, guest did not execute EOI yet.
2518          * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2519          *      -> host enabled PV EOI, guest executed EOI.
2520          */
2521         BUG_ON(!pv_eoi_enabled(vcpu));
2522         pending = pv_eoi_get_pending(vcpu);
2523         /*
2524          * Clear pending bit in any case: it will be set again on vmentry.
2525          * While this might not be ideal from performance point of view,
2526          * this makes sure pv eoi is only enabled when we know it's safe.
2527          */
2528         pv_eoi_clr_pending(vcpu);
2529         if (pending)
2530                 return;
2531         vector = apic_set_eoi(apic);
2532         trace_kvm_pv_eoi(apic, vector);
2533 }
2534
2535 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2536 {
2537         u32 data;
2538
2539         if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2540                 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2541
2542         if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2543                 return;
2544
2545         if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2546                                   sizeof(u32)))
2547                 return;
2548
2549         apic_set_tpr(vcpu->arch.apic, data & 0xff);
2550 }
2551
2552 /*
2553  * apic_sync_pv_eoi_to_guest - called before vmentry
2554  *
2555  * Detect whether it's safe to enable PV EOI and
2556  * if yes do so.
2557  */
2558 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2559                                         struct kvm_lapic *apic)
2560 {
2561         if (!pv_eoi_enabled(vcpu) ||
2562             /* IRR set or many bits in ISR: could be nested. */
2563             apic->irr_pending ||
2564             /* Cache not set: could be safe but we don't bother. */
2565             apic->highest_isr_cache == -1 ||
2566             /* Need EOI to update ioapic. */
2567             kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2568                 /*
2569                  * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2570                  * so we need not do anything here.
2571                  */
2572                 return;
2573         }
2574
2575         pv_eoi_set_pending(apic->vcpu);
2576 }
2577
2578 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2579 {
2580         u32 data, tpr;
2581         int max_irr, max_isr;
2582         struct kvm_lapic *apic = vcpu->arch.apic;
2583
2584         apic_sync_pv_eoi_to_guest(vcpu, apic);
2585
2586         if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2587                 return;
2588
2589         tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2590         max_irr = apic_find_highest_irr(apic);
2591         if (max_irr < 0)
2592                 max_irr = 0;
2593         max_isr = apic_find_highest_isr(apic);
2594         if (max_isr < 0)
2595                 max_isr = 0;
2596         data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2597
2598         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2599                                 sizeof(u32));
2600 }
2601
2602 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2603 {
2604         if (vapic_addr) {
2605                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2606                                         &vcpu->arch.apic->vapic_cache,
2607                                         vapic_addr, sizeof(u32)))
2608                         return -EINVAL;
2609                 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2610         } else {
2611                 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2612         }
2613
2614         vcpu->arch.apic->vapic_addr = vapic_addr;
2615         return 0;
2616 }
2617
2618 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2619 {
2620         struct kvm_lapic *apic = vcpu->arch.apic;
2621         u32 reg = (msr - APIC_BASE_MSR) << 4;
2622
2623         if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2624                 return 1;
2625
2626         if (reg == APIC_ICR2)
2627                 return 1;
2628
2629         /* if this is ICR write vector before command */
2630         if (reg == APIC_ICR)
2631                 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2632         return kvm_lapic_reg_write(apic, reg, (u32)data);
2633 }
2634
2635 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2636 {
2637         struct kvm_lapic *apic = vcpu->arch.apic;
2638         u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
2639
2640         if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2641                 return 1;
2642
2643         if (reg == APIC_DFR || reg == APIC_ICR2)
2644                 return 1;
2645
2646         if (kvm_lapic_reg_read(apic, reg, 4, &low))
2647                 return 1;
2648         if (reg == APIC_ICR)
2649                 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2650
2651         *data = (((u64)high) << 32) | low;
2652
2653         return 0;
2654 }
2655
2656 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2657 {
2658         struct kvm_lapic *apic = vcpu->arch.apic;
2659
2660         if (!lapic_in_kernel(vcpu))
2661                 return 1;
2662
2663         /* if this is ICR write vector before command */
2664         if (reg == APIC_ICR)
2665                 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2666         return kvm_lapic_reg_write(apic, reg, (u32)data);
2667 }
2668
2669 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2670 {
2671         struct kvm_lapic *apic = vcpu->arch.apic;
2672         u32 low, high = 0;
2673
2674         if (!lapic_in_kernel(vcpu))
2675                 return 1;
2676
2677         if (kvm_lapic_reg_read(apic, reg, 4, &low))
2678                 return 1;
2679         if (reg == APIC_ICR)
2680                 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2681
2682         *data = (((u64)high) << 32) | low;
2683
2684         return 0;
2685 }
2686
2687 int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
2688 {
2689         u64 addr = data & ~KVM_MSR_ENABLED;
2690         struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
2691         unsigned long new_len;
2692
2693         if (!IS_ALIGNED(addr, 4))
2694                 return 1;
2695
2696         vcpu->arch.pv_eoi.msr_val = data;
2697         if (!pv_eoi_enabled(vcpu))
2698                 return 0;
2699
2700         if (addr == ghc->gpa && len <= ghc->len)
2701                 new_len = ghc->len;
2702         else
2703                 new_len = len;
2704
2705         return kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
2706 }
2707
2708 void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2709 {
2710         struct kvm_lapic *apic = vcpu->arch.apic;
2711         u8 sipi_vector;
2712         unsigned long pe;
2713
2714         if (!lapic_in_kernel(vcpu) || !apic->pending_events)
2715                 return;
2716
2717         /*
2718          * INITs are latched while CPU is in specific states
2719          * (SMM, VMX non-root mode, SVM with GIF=0).
2720          * Because a CPU cannot be in these states immediately
2721          * after it has processed an INIT signal (and thus in
2722          * KVM_MP_STATE_INIT_RECEIVED state), just eat SIPIs
2723          * and leave the INIT pending.
2724          */
2725         if (is_smm(vcpu) || kvm_x86_ops->apic_init_signal_blocked(vcpu)) {
2726                 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2727                 if (test_bit(KVM_APIC_SIPI, &apic->pending_events))
2728                         clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2729                 return;
2730         }
2731
2732         pe = xchg(&apic->pending_events, 0);
2733         if (test_bit(KVM_APIC_INIT, &pe)) {
2734                 kvm_vcpu_reset(vcpu, true);
2735                 if (kvm_vcpu_is_bsp(apic->vcpu))
2736                         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2737                 else
2738                         vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2739         }
2740         if (test_bit(KVM_APIC_SIPI, &pe) &&
2741             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
2742                 /* evaluate pending_events before reading the vector */
2743                 smp_rmb();
2744                 sipi_vector = apic->sipi_vector;
2745                 kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
2746                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2747         }
2748 }
2749
2750 void kvm_lapic_init(void)
2751 {
2752         /* do not patch jump label more than once per second */
2753         jump_label_rate_limit(&apic_hw_disabled, HZ);
2754         jump_label_rate_limit(&apic_sw_disabled, HZ);
2755 }
2756
2757 void kvm_lapic_exit(void)
2758 {
2759         static_key_deferred_flush(&apic_hw_disabled);
2760         static_key_deferred_flush(&apic_sw_disabled);
2761 }