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