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