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