GNU Linux-libre 4.14.324-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                 if (KVM_BUG_ON(!src, kvm)) {
898                         *r = 0;
899                         return true;
900                 }
901                 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
902                 return true;
903         }
904
905         rcu_read_lock();
906         map = rcu_dereference(kvm->arch.apic_map);
907
908         ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
909         if (ret)
910                 for_each_set_bit(i, &bitmap, 16) {
911                         if (!dst[i])
912                                 continue;
913                         if (*r < 0)
914                                 *r = 0;
915                         *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
916                 }
917
918         rcu_read_unlock();
919         return ret;
920 }
921
922 /*
923  * This routine tries to handler interrupts in posted mode, here is how
924  * it deals with different cases:
925  * - For single-destination interrupts, handle it in posted mode
926  * - Else if vector hashing is enabled and it is a lowest-priority
927  *   interrupt, handle it in posted mode and use the following mechanism
928  *   to find the destinaiton vCPU.
929  *      1. For lowest-priority interrupts, store all the possible
930  *         destination vCPUs in an array.
931  *      2. Use "guest vector % max number of destination vCPUs" to find
932  *         the right destination vCPU in the array for the lowest-priority
933  *         interrupt.
934  * - Otherwise, use remapped mode to inject the interrupt.
935  */
936 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
937                         struct kvm_vcpu **dest_vcpu)
938 {
939         struct kvm_apic_map *map;
940         unsigned long bitmap;
941         struct kvm_lapic **dst = NULL;
942         bool ret = false;
943
944         if (irq->shorthand)
945                 return false;
946
947         rcu_read_lock();
948         map = rcu_dereference(kvm->arch.apic_map);
949
950         if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
951                         hweight16(bitmap) == 1) {
952                 unsigned long i = find_first_bit(&bitmap, 16);
953
954                 if (dst[i]) {
955                         *dest_vcpu = dst[i]->vcpu;
956                         ret = true;
957                 }
958         }
959
960         rcu_read_unlock();
961         return ret;
962 }
963
964 /*
965  * Add a pending IRQ into lapic.
966  * Return 1 if successfully added and 0 if discarded.
967  */
968 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
969                              int vector, int level, int trig_mode,
970                              struct dest_map *dest_map)
971 {
972         int result = 0;
973         struct kvm_vcpu *vcpu = apic->vcpu;
974
975         trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
976                                   trig_mode, vector);
977         switch (delivery_mode) {
978         case APIC_DM_LOWEST:
979                 vcpu->arch.apic_arb_prio++;
980         case APIC_DM_FIXED:
981                 if (unlikely(trig_mode && !level))
982                         break;
983
984                 /* FIXME add logic for vcpu on reset */
985                 if (unlikely(!apic_enabled(apic)))
986                         break;
987
988                 result = 1;
989
990                 if (dest_map) {
991                         __set_bit(vcpu->vcpu_id, dest_map->map);
992                         dest_map->vectors[vcpu->vcpu_id] = vector;
993                 }
994
995                 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
996                         if (trig_mode)
997                                 kvm_lapic_set_vector(vector, apic->regs + APIC_TMR);
998                         else
999                                 apic_clear_vector(vector, apic->regs + APIC_TMR);
1000                 }
1001
1002                 if (kvm_x86_ops->deliver_posted_interrupt(vcpu, vector)) {
1003                         kvm_lapic_set_irr(vector, apic);
1004                         kvm_make_request(KVM_REQ_EVENT, vcpu);
1005                         kvm_vcpu_kick(vcpu);
1006                 }
1007                 break;
1008
1009         case APIC_DM_REMRD:
1010                 result = 1;
1011                 vcpu->arch.pv.pv_unhalted = 1;
1012                 kvm_make_request(KVM_REQ_EVENT, vcpu);
1013                 kvm_vcpu_kick(vcpu);
1014                 break;
1015
1016         case APIC_DM_SMI:
1017                 result = 1;
1018                 kvm_make_request(KVM_REQ_SMI, vcpu);
1019                 kvm_vcpu_kick(vcpu);
1020                 break;
1021
1022         case APIC_DM_NMI:
1023                 result = 1;
1024                 kvm_inject_nmi(vcpu);
1025                 kvm_vcpu_kick(vcpu);
1026                 break;
1027
1028         case APIC_DM_INIT:
1029                 if (!trig_mode || level) {
1030                         result = 1;
1031                         /* assumes that there are only KVM_APIC_INIT/SIPI */
1032                         apic->pending_events = (1UL << KVM_APIC_INIT);
1033                         /* make sure pending_events is visible before sending
1034                          * the request */
1035                         smp_wmb();
1036                         kvm_make_request(KVM_REQ_EVENT, vcpu);
1037                         kvm_vcpu_kick(vcpu);
1038                 } else {
1039                         apic_debug("Ignoring de-assert INIT to vcpu %d\n",
1040                                    vcpu->vcpu_id);
1041                 }
1042                 break;
1043
1044         case APIC_DM_STARTUP:
1045                 apic_debug("SIPI to vcpu %d vector 0x%02x\n",
1046                            vcpu->vcpu_id, vector);
1047                 result = 1;
1048                 apic->sipi_vector = vector;
1049                 /* make sure sipi_vector is visible for the receiver */
1050                 smp_wmb();
1051                 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1052                 kvm_make_request(KVM_REQ_EVENT, vcpu);
1053                 kvm_vcpu_kick(vcpu);
1054                 break;
1055
1056         case APIC_DM_EXTINT:
1057                 /*
1058                  * Should only be called by kvm_apic_local_deliver() with LVT0,
1059                  * before NMI watchdog was enabled. Already handled by
1060                  * kvm_apic_accept_pic_intr().
1061                  */
1062                 break;
1063
1064         default:
1065                 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1066                        delivery_mode);
1067                 break;
1068         }
1069         return result;
1070 }
1071
1072 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1073 {
1074         return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1075 }
1076
1077 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1078 {
1079         return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1080 }
1081
1082 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1083 {
1084         int trigger_mode;
1085
1086         /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1087         if (!kvm_ioapic_handles_vector(apic, vector))
1088                 return;
1089
1090         /* Request a KVM exit to inform the userspace IOAPIC. */
1091         if (irqchip_split(apic->vcpu->kvm)) {
1092                 apic->vcpu->arch.pending_ioapic_eoi = vector;
1093                 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1094                 return;
1095         }
1096
1097         if (apic_test_vector(vector, apic->regs + APIC_TMR))
1098                 trigger_mode = IOAPIC_LEVEL_TRIG;
1099         else
1100                 trigger_mode = IOAPIC_EDGE_TRIG;
1101
1102         kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1103 }
1104
1105 static int apic_set_eoi(struct kvm_lapic *apic)
1106 {
1107         int vector = apic_find_highest_isr(apic);
1108
1109         trace_kvm_eoi(apic, vector);
1110
1111         /*
1112          * Not every write EOI will has corresponding ISR,
1113          * one example is when Kernel check timer on setup_IO_APIC
1114          */
1115         if (vector == -1)
1116                 return vector;
1117
1118         apic_clear_isr(vector, apic);
1119         apic_update_ppr(apic);
1120
1121         if (test_bit(vector, vcpu_to_synic(apic->vcpu)->vec_bitmap))
1122                 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1123
1124         kvm_ioapic_send_eoi(apic, vector);
1125         kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1126         return vector;
1127 }
1128
1129 /*
1130  * this interface assumes a trap-like exit, which has already finished
1131  * desired side effect including vISR and vPPR update.
1132  */
1133 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1134 {
1135         struct kvm_lapic *apic = vcpu->arch.apic;
1136
1137         trace_kvm_eoi(apic, vector);
1138
1139         kvm_ioapic_send_eoi(apic, vector);
1140         kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1141 }
1142 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1143
1144 static void apic_send_ipi(struct kvm_lapic *apic)
1145 {
1146         u32 icr_low = kvm_lapic_get_reg(apic, APIC_ICR);
1147         u32 icr_high = kvm_lapic_get_reg(apic, APIC_ICR2);
1148         struct kvm_lapic_irq irq;
1149
1150         irq.vector = icr_low & APIC_VECTOR_MASK;
1151         irq.delivery_mode = icr_low & APIC_MODE_MASK;
1152         irq.dest_mode = icr_low & APIC_DEST_MASK;
1153         irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1154         irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1155         irq.shorthand = icr_low & APIC_SHORT_MASK;
1156         irq.msi_redir_hint = false;
1157         if (apic_x2apic_mode(apic))
1158                 irq.dest_id = icr_high;
1159         else
1160                 irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1161
1162         trace_kvm_apic_ipi(icr_low, irq.dest_id);
1163
1164         apic_debug("icr_high 0x%x, icr_low 0x%x, "
1165                    "short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
1166                    "dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x, "
1167                    "msi_redir_hint 0x%x\n",
1168                    icr_high, icr_low, irq.shorthand, irq.dest_id,
1169                    irq.trig_mode, irq.level, irq.dest_mode, irq.delivery_mode,
1170                    irq.vector, irq.msi_redir_hint);
1171
1172         kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1173 }
1174
1175 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1176 {
1177         ktime_t remaining, now;
1178         s64 ns;
1179         u32 tmcct;
1180
1181         ASSERT(apic != NULL);
1182
1183         /* if initial count is 0, current count should also be 0 */
1184         if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1185                 apic->lapic_timer.period == 0)
1186                 return 0;
1187
1188         now = ktime_get();
1189         remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1190         if (ktime_to_ns(remaining) < 0)
1191                 remaining = 0;
1192
1193         ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1194         tmcct = div64_u64(ns,
1195                          (APIC_BUS_CYCLE_NS * apic->divide_count));
1196
1197         return tmcct;
1198 }
1199
1200 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1201 {
1202         struct kvm_vcpu *vcpu = apic->vcpu;
1203         struct kvm_run *run = vcpu->run;
1204
1205         kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1206         run->tpr_access.rip = kvm_rip_read(vcpu);
1207         run->tpr_access.is_write = write;
1208 }
1209
1210 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1211 {
1212         if (apic->vcpu->arch.tpr_access_reporting)
1213                 __report_tpr_access(apic, write);
1214 }
1215
1216 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1217 {
1218         u32 val = 0;
1219
1220         if (offset >= LAPIC_MMIO_LENGTH)
1221                 return 0;
1222
1223         switch (offset) {
1224         case APIC_ARBPRI:
1225                 apic_debug("Access APIC ARBPRI register which is for P6\n");
1226                 break;
1227
1228         case APIC_TMCCT:        /* Timer CCR */
1229                 if (apic_lvtt_tscdeadline(apic))
1230                         return 0;
1231
1232                 val = apic_get_tmcct(apic);
1233                 break;
1234         case APIC_PROCPRI:
1235                 apic_update_ppr(apic);
1236                 val = kvm_lapic_get_reg(apic, offset);
1237                 break;
1238         case APIC_TASKPRI:
1239                 report_tpr_access(apic, false);
1240                 /* fall thru */
1241         default:
1242                 val = kvm_lapic_get_reg(apic, offset);
1243                 break;
1244         }
1245
1246         return val;
1247 }
1248
1249 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1250 {
1251         return container_of(dev, struct kvm_lapic, dev);
1252 }
1253
1254 int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1255                 void *data)
1256 {
1257         unsigned char alignment = offset & 0xf;
1258         u32 result;
1259         /* this bitmask has a bit cleared for each reserved register */
1260         static const u64 rmask = 0x43ff01ffffffe70cULL;
1261
1262         if ((alignment + len) > 4) {
1263                 apic_debug("KVM_APIC_READ: alignment error %x %d\n",
1264                            offset, len);
1265                 return 1;
1266         }
1267
1268         if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
1269                 apic_debug("KVM_APIC_READ: read reserved register %x\n",
1270                            offset);
1271                 return 1;
1272         }
1273
1274         result = __apic_read(apic, offset & ~0xf);
1275
1276         trace_kvm_apic_read(offset, result);
1277
1278         switch (len) {
1279         case 1:
1280         case 2:
1281         case 4:
1282                 memcpy(data, (char *)&result + alignment, len);
1283                 break;
1284         default:
1285                 printk(KERN_ERR "Local APIC read with len = %x, "
1286                        "should be 1,2, or 4 instead\n", len);
1287                 break;
1288         }
1289         return 0;
1290 }
1291 EXPORT_SYMBOL_GPL(kvm_lapic_reg_read);
1292
1293 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1294 {
1295         return addr >= apic->base_address &&
1296                 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1297 }
1298
1299 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1300                            gpa_t address, int len, void *data)
1301 {
1302         struct kvm_lapic *apic = to_lapic(this);
1303         u32 offset = address - apic->base_address;
1304
1305         if (!apic_mmio_in_range(apic, address))
1306                 return -EOPNOTSUPP;
1307
1308         if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1309                 if (!kvm_check_has_quirk(vcpu->kvm,
1310                                          KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1311                         return -EOPNOTSUPP;
1312
1313                 memset(data, 0xff, len);
1314                 return 0;
1315         }
1316
1317         kvm_lapic_reg_read(apic, offset, len, data);
1318
1319         return 0;
1320 }
1321
1322 static void update_divide_count(struct kvm_lapic *apic)
1323 {
1324         u32 tmp1, tmp2, tdcr;
1325
1326         tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1327         tmp1 = tdcr & 0xf;
1328         tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1329         apic->divide_count = 0x1 << (tmp2 & 0x7);
1330
1331         apic_debug("timer divide count is 0x%x\n",
1332                                    apic->divide_count);
1333 }
1334
1335 static void apic_update_lvtt(struct kvm_lapic *apic)
1336 {
1337         u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1338                         apic->lapic_timer.timer_mode_mask;
1339
1340         if (apic->lapic_timer.timer_mode != timer_mode) {
1341                 apic->lapic_timer.timer_mode = timer_mode;
1342                 hrtimer_cancel(&apic->lapic_timer.timer);
1343         }
1344 }
1345
1346 static void apic_timer_expired(struct kvm_lapic *apic)
1347 {
1348         struct kvm_vcpu *vcpu = apic->vcpu;
1349         struct swait_queue_head *q = &vcpu->wq;
1350         struct kvm_timer *ktimer = &apic->lapic_timer;
1351
1352         if (atomic_read(&apic->lapic_timer.pending))
1353                 return;
1354
1355         atomic_inc(&apic->lapic_timer.pending);
1356         kvm_set_pending_timer(vcpu);
1357
1358         /*
1359          * For x86, the atomic_inc() is serialized, thus
1360          * using swait_active() is safe.
1361          */
1362         if (swait_active(q))
1363                 swake_up(q);
1364
1365         if (apic_lvtt_tscdeadline(apic))
1366                 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1367 }
1368
1369 /*
1370  * On APICv, this test will cause a busy wait
1371  * during a higher-priority task.
1372  */
1373
1374 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1375 {
1376         struct kvm_lapic *apic = vcpu->arch.apic;
1377         u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1378
1379         if (kvm_apic_hw_enabled(apic)) {
1380                 int vec = reg & APIC_VECTOR_MASK;
1381                 void *bitmap = apic->regs + APIC_ISR;
1382
1383                 if (vcpu->arch.apicv_active)
1384                         bitmap = apic->regs + APIC_IRR;
1385
1386                 if (apic_test_vector(vec, bitmap))
1387                         return true;
1388         }
1389         return false;
1390 }
1391
1392 void wait_lapic_expire(struct kvm_vcpu *vcpu)
1393 {
1394         struct kvm_lapic *apic = vcpu->arch.apic;
1395         u64 guest_tsc, tsc_deadline;
1396
1397         if (!lapic_in_kernel(vcpu))
1398                 return;
1399
1400         if (apic->lapic_timer.expired_tscdeadline == 0)
1401                 return;
1402
1403         if (!lapic_timer_int_injected(vcpu))
1404                 return;
1405
1406         tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1407         apic->lapic_timer.expired_tscdeadline = 0;
1408         guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1409         trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1410
1411         /* __delay is delay_tsc whenever the hardware has TSC, thus always.  */
1412         if (guest_tsc < tsc_deadline)
1413                 __delay(min(tsc_deadline - guest_tsc,
1414                         nsec_to_cycles(vcpu, lapic_timer_advance_ns)));
1415 }
1416
1417 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1418 {
1419         u64 guest_tsc, tscdeadline = apic->lapic_timer.tscdeadline;
1420         u64 ns = 0;
1421         ktime_t expire;
1422         struct kvm_vcpu *vcpu = apic->vcpu;
1423         unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1424         unsigned long flags;
1425         ktime_t now;
1426
1427         if (unlikely(!tscdeadline || !this_tsc_khz))
1428                 return;
1429
1430         local_irq_save(flags);
1431
1432         now = ktime_get();
1433         guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1434         if (likely(tscdeadline > guest_tsc)) {
1435                 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1436                 do_div(ns, this_tsc_khz);
1437                 expire = ktime_add_ns(now, ns);
1438                 expire = ktime_sub_ns(expire, lapic_timer_advance_ns);
1439                 hrtimer_start(&apic->lapic_timer.timer,
1440                                 expire, HRTIMER_MODE_ABS_PINNED);
1441         } else
1442                 apic_timer_expired(apic);
1443
1444         local_irq_restore(flags);
1445 }
1446
1447 static bool set_target_expiration(struct kvm_lapic *apic)
1448 {
1449         ktime_t now;
1450         u64 tscl = rdtsc();
1451
1452         now = ktime_get();
1453         apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1454                 * APIC_BUS_CYCLE_NS * apic->divide_count;
1455
1456         if (!apic->lapic_timer.period)
1457                 return false;
1458
1459         /*
1460          * Do not allow the guest to program periodic timers with small
1461          * interval, since the hrtimers are not throttled by the host
1462          * scheduler.
1463          */
1464         if (apic_lvtt_period(apic)) {
1465                 s64 min_period = min_timer_period_us * 1000LL;
1466
1467                 if (apic->lapic_timer.period < min_period) {
1468                         pr_info_ratelimited(
1469                             "kvm: vcpu %i: requested %lld ns "
1470                             "lapic timer period limited to %lld ns\n",
1471                             apic->vcpu->vcpu_id,
1472                             apic->lapic_timer.period, min_period);
1473                         apic->lapic_timer.period = min_period;
1474                 }
1475         }
1476
1477         apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
1478                    PRIx64 ", "
1479                    "timer initial count 0x%x, period %lldns, "
1480                    "expire @ 0x%016" PRIx64 ".\n", __func__,
1481                    APIC_BUS_CYCLE_NS, ktime_to_ns(now),
1482                    kvm_lapic_get_reg(apic, APIC_TMICT),
1483                    apic->lapic_timer.period,
1484                    ktime_to_ns(ktime_add_ns(now,
1485                                 apic->lapic_timer.period)));
1486
1487         apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1488                 nsec_to_cycles(apic->vcpu, apic->lapic_timer.period);
1489         apic->lapic_timer.target_expiration = ktime_add_ns(now, apic->lapic_timer.period);
1490
1491         return true;
1492 }
1493
1494 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1495 {
1496         ktime_t now = ktime_get();
1497         u64 tscl = rdtsc();
1498         ktime_t delta;
1499
1500         /*
1501          * Synchronize both deadlines to the same time source or
1502          * differences in the periods (caused by differences in the
1503          * underlying clocks or numerical approximation errors) will
1504          * cause the two to drift apart over time as the errors
1505          * accumulate.
1506          */
1507         apic->lapic_timer.target_expiration =
1508                 ktime_add_ns(apic->lapic_timer.target_expiration,
1509                                 apic->lapic_timer.period);
1510         delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1511         apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1512                 nsec_to_cycles(apic->vcpu, delta);
1513 }
1514
1515 static void start_sw_period(struct kvm_lapic *apic)
1516 {
1517         if (!apic->lapic_timer.period)
1518                 return;
1519
1520         if (ktime_after(ktime_get(),
1521                         apic->lapic_timer.target_expiration)) {
1522                 apic_timer_expired(apic);
1523
1524                 if (apic_lvtt_oneshot(apic))
1525                         return;
1526
1527                 advance_periodic_target_expiration(apic);
1528         }
1529
1530         hrtimer_start(&apic->lapic_timer.timer,
1531                 apic->lapic_timer.target_expiration,
1532                 HRTIMER_MODE_ABS_PINNED);
1533 }
1534
1535 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1536 {
1537         if (!lapic_in_kernel(vcpu))
1538                 return false;
1539
1540         return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1541 }
1542 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1543
1544 static void cancel_hv_timer(struct kvm_lapic *apic)
1545 {
1546         WARN_ON(preemptible());
1547         WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1548         kvm_x86_ops->cancel_hv_timer(apic->vcpu);
1549         apic->lapic_timer.hv_timer_in_use = false;
1550 }
1551
1552 static bool start_hv_timer(struct kvm_lapic *apic)
1553 {
1554         struct kvm_timer *ktimer = &apic->lapic_timer;
1555         int r;
1556
1557         WARN_ON(preemptible());
1558         if (!kvm_x86_ops->set_hv_timer)
1559                 return false;
1560
1561         if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1562                 return false;
1563
1564         r = kvm_x86_ops->set_hv_timer(apic->vcpu, ktimer->tscdeadline);
1565         if (r < 0)
1566                 return false;
1567
1568         ktimer->hv_timer_in_use = true;
1569         hrtimer_cancel(&ktimer->timer);
1570
1571         /*
1572          * Also recheck ktimer->pending, in case the sw timer triggered in
1573          * the window.  For periodic timer, leave the hv timer running for
1574          * simplicity, and the deadline will be recomputed on the next vmexit.
1575          */
1576         if (!apic_lvtt_period(apic) && (r || atomic_read(&ktimer->pending))) {
1577                 if (r)
1578                         apic_timer_expired(apic);
1579                 return false;
1580         }
1581
1582         trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, true);
1583         return true;
1584 }
1585
1586 static void start_sw_timer(struct kvm_lapic *apic)
1587 {
1588         struct kvm_timer *ktimer = &apic->lapic_timer;
1589
1590         WARN_ON(preemptible());
1591         if (apic->lapic_timer.hv_timer_in_use)
1592                 cancel_hv_timer(apic);
1593         if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1594                 return;
1595
1596         if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1597                 start_sw_period(apic);
1598         else if (apic_lvtt_tscdeadline(apic))
1599                 start_sw_tscdeadline(apic);
1600         trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1601 }
1602
1603 static void restart_apic_timer(struct kvm_lapic *apic)
1604 {
1605         preempt_disable();
1606         if (!start_hv_timer(apic))
1607                 start_sw_timer(apic);
1608         preempt_enable();
1609 }
1610
1611 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1612 {
1613         struct kvm_lapic *apic = vcpu->arch.apic;
1614
1615         preempt_disable();
1616         /* If the preempt notifier has already run, it also called apic_timer_expired */
1617         if (!apic->lapic_timer.hv_timer_in_use)
1618                 goto out;
1619         WARN_ON(swait_active(&vcpu->wq));
1620         cancel_hv_timer(apic);
1621         apic_timer_expired(apic);
1622
1623         if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1624                 advance_periodic_target_expiration(apic);
1625                 restart_apic_timer(apic);
1626         }
1627 out:
1628         preempt_enable();
1629 }
1630 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1631
1632 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1633 {
1634         restart_apic_timer(vcpu->arch.apic);
1635 }
1636 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_hv_timer);
1637
1638 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1639 {
1640         struct kvm_lapic *apic = vcpu->arch.apic;
1641
1642         preempt_disable();
1643         /* Possibly the TSC deadline timer is not enabled yet */
1644         if (apic->lapic_timer.hv_timer_in_use)
1645                 start_sw_timer(apic);
1646         preempt_enable();
1647 }
1648 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_sw_timer);
1649
1650 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
1651 {
1652         struct kvm_lapic *apic = vcpu->arch.apic;
1653
1654         WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1655         restart_apic_timer(apic);
1656 }
1657
1658 static void start_apic_timer(struct kvm_lapic *apic)
1659 {
1660         atomic_set(&apic->lapic_timer.pending, 0);
1661
1662         if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1663             && !set_target_expiration(apic))
1664                 return;
1665
1666         restart_apic_timer(apic);
1667 }
1668
1669 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
1670 {
1671         bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
1672
1673         if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
1674                 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
1675                 if (lvt0_in_nmi_mode) {
1676                         apic_debug("Receive NMI setting on APIC_LVT0 "
1677                                    "for cpu %d\n", apic->vcpu->vcpu_id);
1678                         atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1679                 } else
1680                         atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1681         }
1682 }
1683
1684 int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
1685 {
1686         int ret = 0;
1687
1688         trace_kvm_apic_write(reg, val);
1689
1690         switch (reg) {
1691         case APIC_ID:           /* Local APIC ID */
1692                 if (!apic_x2apic_mode(apic))
1693                         kvm_apic_set_xapic_id(apic, val >> 24);
1694                 else
1695                         ret = 1;
1696                 break;
1697
1698         case APIC_TASKPRI:
1699                 report_tpr_access(apic, true);
1700                 apic_set_tpr(apic, val & 0xff);
1701                 break;
1702
1703         case APIC_EOI:
1704                 apic_set_eoi(apic);
1705                 break;
1706
1707         case APIC_LDR:
1708                 if (!apic_x2apic_mode(apic))
1709                         kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
1710                 else
1711                         ret = 1;
1712                 break;
1713
1714         case APIC_DFR:
1715                 if (!apic_x2apic_mode(apic)) {
1716                         kvm_lapic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
1717                         recalculate_apic_map(apic->vcpu->kvm);
1718                 } else
1719                         ret = 1;
1720                 break;
1721
1722         case APIC_SPIV: {
1723                 u32 mask = 0x3ff;
1724                 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
1725                         mask |= APIC_SPIV_DIRECTED_EOI;
1726                 apic_set_spiv(apic, val & mask);
1727                 if (!(val & APIC_SPIV_APIC_ENABLED)) {
1728                         int i;
1729                         u32 lvt_val;
1730
1731                         for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
1732                                 lvt_val = kvm_lapic_get_reg(apic,
1733                                                        APIC_LVTT + 0x10 * i);
1734                                 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
1735                                              lvt_val | APIC_LVT_MASKED);
1736                         }
1737                         apic_update_lvtt(apic);
1738                         atomic_set(&apic->lapic_timer.pending, 0);
1739
1740                 }
1741                 break;
1742         }
1743         case APIC_ICR:
1744                 /* No delay here, so we always clear the pending bit */
1745                 kvm_lapic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
1746                 apic_send_ipi(apic);
1747                 break;
1748
1749         case APIC_ICR2:
1750                 if (!apic_x2apic_mode(apic))
1751                         val &= 0xff000000;
1752                 kvm_lapic_set_reg(apic, APIC_ICR2, val);
1753                 break;
1754
1755         case APIC_LVT0:
1756                 apic_manage_nmi_watchdog(apic, val);
1757         case APIC_LVTTHMR:
1758         case APIC_LVTPC:
1759         case APIC_LVT1:
1760         case APIC_LVTERR: {
1761                 /* TODO: Check vector */
1762                 size_t size;
1763                 u32 index;
1764
1765                 if (!kvm_apic_sw_enabled(apic))
1766                         val |= APIC_LVT_MASKED;
1767                 size = ARRAY_SIZE(apic_lvt_mask);
1768                 index = array_index_nospec(
1769                                 (reg - APIC_LVTT) >> 4, size);
1770                 val &= apic_lvt_mask[index];
1771                 kvm_lapic_set_reg(apic, reg, val);
1772                 break;
1773         }
1774
1775         case APIC_LVTT:
1776                 if (!kvm_apic_sw_enabled(apic))
1777                         val |= APIC_LVT_MASKED;
1778                 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
1779                 kvm_lapic_set_reg(apic, APIC_LVTT, val);
1780                 apic_update_lvtt(apic);
1781                 break;
1782
1783         case APIC_TMICT:
1784                 if (apic_lvtt_tscdeadline(apic))
1785                         break;
1786
1787                 hrtimer_cancel(&apic->lapic_timer.timer);
1788                 kvm_lapic_set_reg(apic, APIC_TMICT, val);
1789                 start_apic_timer(apic);
1790                 break;
1791
1792         case APIC_TDCR:
1793                 if (val & 4)
1794                         apic_debug("KVM_WRITE:TDCR %x\n", val);
1795                 kvm_lapic_set_reg(apic, APIC_TDCR, val);
1796                 update_divide_count(apic);
1797                 break;
1798
1799         case APIC_ESR:
1800                 if (apic_x2apic_mode(apic) && val != 0) {
1801                         apic_debug("KVM_WRITE:ESR not zero %x\n", val);
1802                         ret = 1;
1803                 }
1804                 break;
1805
1806         case APIC_SELF_IPI:
1807                 if (apic_x2apic_mode(apic)) {
1808                         kvm_lapic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
1809                 } else
1810                         ret = 1;
1811                 break;
1812         default:
1813                 ret = 1;
1814                 break;
1815         }
1816         if (ret)
1817                 apic_debug("Local APIC Write to read-only register %x\n", reg);
1818         return ret;
1819 }
1820 EXPORT_SYMBOL_GPL(kvm_lapic_reg_write);
1821
1822 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1823                             gpa_t address, int len, const void *data)
1824 {
1825         struct kvm_lapic *apic = to_lapic(this);
1826         unsigned int offset = address - apic->base_address;
1827         u32 val;
1828
1829         if (!apic_mmio_in_range(apic, address))
1830                 return -EOPNOTSUPP;
1831
1832         if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1833                 if (!kvm_check_has_quirk(vcpu->kvm,
1834                                          KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1835                         return -EOPNOTSUPP;
1836
1837                 return 0;
1838         }
1839
1840         /*
1841          * APIC register must be aligned on 128-bits boundary.
1842          * 32/64/128 bits registers must be accessed thru 32 bits.
1843          * Refer SDM 8.4.1
1844          */
1845         if (len != 4 || (offset & 0xf)) {
1846                 /* Don't shout loud, $infamous_os would cause only noise. */
1847                 apic_debug("apic write: bad size=%d %lx\n", len, (long)address);
1848                 return 0;
1849         }
1850
1851         val = *(u32*)data;
1852
1853         /* too common printing */
1854         if (offset != APIC_EOI)
1855                 apic_debug("%s: offset 0x%x with length 0x%x, and value is "
1856                            "0x%x\n", __func__, offset, len, val);
1857
1858         kvm_lapic_reg_write(apic, offset & 0xff0, val);
1859
1860         return 0;
1861 }
1862
1863 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
1864 {
1865         kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
1866 }
1867 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
1868
1869 /* emulate APIC access in a trap manner */
1870 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
1871 {
1872         u32 val = 0;
1873
1874         /* hw has done the conditional check and inst decode */
1875         offset &= 0xff0;
1876
1877         kvm_lapic_reg_read(vcpu->arch.apic, offset, 4, &val);
1878
1879         /* TODO: optimize to just emulate side effect w/o one more write */
1880         kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
1881 }
1882 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
1883
1884 void kvm_free_lapic(struct kvm_vcpu *vcpu)
1885 {
1886         struct kvm_lapic *apic = vcpu->arch.apic;
1887
1888         if (!vcpu->arch.apic)
1889                 return;
1890
1891         hrtimer_cancel(&apic->lapic_timer.timer);
1892
1893         if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
1894                 static_key_slow_dec_deferred(&apic_hw_disabled);
1895
1896         if (!apic->sw_enabled)
1897                 static_key_slow_dec_deferred(&apic_sw_disabled);
1898
1899         if (apic->regs)
1900                 free_page((unsigned long)apic->regs);
1901
1902         kfree(apic);
1903 }
1904
1905 /*
1906  *----------------------------------------------------------------------
1907  * LAPIC interface
1908  *----------------------------------------------------------------------
1909  */
1910 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
1911 {
1912         struct kvm_lapic *apic = vcpu->arch.apic;
1913
1914         if (!lapic_in_kernel(vcpu) ||
1915                 !apic_lvtt_tscdeadline(apic))
1916                 return 0;
1917
1918         return apic->lapic_timer.tscdeadline;
1919 }
1920
1921 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
1922 {
1923         struct kvm_lapic *apic = vcpu->arch.apic;
1924
1925         if (!kvm_apic_present(vcpu) || apic_lvtt_oneshot(apic) ||
1926                         apic_lvtt_period(apic))
1927                 return;
1928
1929         hrtimer_cancel(&apic->lapic_timer.timer);
1930         apic->lapic_timer.tscdeadline = data;
1931         start_apic_timer(apic);
1932 }
1933
1934 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
1935 {
1936         apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
1937 }
1938
1939 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
1940 {
1941         u64 tpr;
1942
1943         tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
1944
1945         return (tpr & 0xf0) >> 4;
1946 }
1947
1948 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
1949 {
1950         u64 old_value = vcpu->arch.apic_base;
1951         struct kvm_lapic *apic = vcpu->arch.apic;
1952
1953         if (!apic)
1954                 value |= MSR_IA32_APICBASE_BSP;
1955
1956         vcpu->arch.apic_base = value;
1957
1958         if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
1959                 kvm_update_cpuid(vcpu);
1960
1961         if (!apic)
1962                 return;
1963
1964         /* update jump label if enable bit changes */
1965         if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
1966                 if (value & MSR_IA32_APICBASE_ENABLE) {
1967                         kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
1968                         static_key_slow_dec_deferred(&apic_hw_disabled);
1969                 } else {
1970                         static_key_slow_inc(&apic_hw_disabled.key);
1971                         recalculate_apic_map(vcpu->kvm);
1972                 }
1973         }
1974
1975         if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
1976                 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
1977
1978         if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE))
1979                 kvm_x86_ops->set_virtual_apic_mode(vcpu);
1980
1981         apic->base_address = apic->vcpu->arch.apic_base &
1982                              MSR_IA32_APICBASE_BASE;
1983
1984         if ((value & MSR_IA32_APICBASE_ENABLE) &&
1985              apic->base_address != APIC_DEFAULT_PHYS_BASE)
1986                 pr_warn_once("APIC base relocation is unsupported by KVM");
1987
1988         /* with FSB delivery interrupt, we can restart APIC functionality */
1989         apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
1990                    "0x%lx.\n", apic->vcpu->arch.apic_base, apic->base_address);
1991
1992 }
1993
1994 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
1995 {
1996         struct kvm_lapic *apic = vcpu->arch.apic;
1997         int i;
1998
1999         if (!apic)
2000                 return;
2001
2002         apic_debug("%s\n", __func__);
2003
2004         /* Stop the timer in case it's a reset to an active apic */
2005         hrtimer_cancel(&apic->lapic_timer.timer);
2006
2007         if (!init_event) {
2008                 kvm_lapic_set_base(vcpu, APIC_DEFAULT_PHYS_BASE |
2009                                          MSR_IA32_APICBASE_ENABLE);
2010                 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2011         }
2012         kvm_apic_set_version(apic->vcpu);
2013
2014         for (i = 0; i < KVM_APIC_LVT_NUM; i++)
2015                 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
2016         apic_update_lvtt(apic);
2017         if (kvm_vcpu_is_reset_bsp(vcpu) &&
2018             kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2019                 kvm_lapic_set_reg(apic, APIC_LVT0,
2020                              SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2021         apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2022
2023         kvm_lapic_set_reg(apic, APIC_DFR, 0xffffffffU);
2024         apic_set_spiv(apic, 0xff);
2025         kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2026         if (!apic_x2apic_mode(apic))
2027                 kvm_apic_set_ldr(apic, 0);
2028         kvm_lapic_set_reg(apic, APIC_ESR, 0);
2029         kvm_lapic_set_reg(apic, APIC_ICR, 0);
2030         kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2031         kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2032         kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2033         for (i = 0; i < 8; i++) {
2034                 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2035                 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2036                 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2037         }
2038         apic->irr_pending = vcpu->arch.apicv_active;
2039         apic->isr_count = vcpu->arch.apicv_active ? 1 : 0;
2040         apic->highest_isr_cache = -1;
2041         update_divide_count(apic);
2042         atomic_set(&apic->lapic_timer.pending, 0);
2043         if (kvm_vcpu_is_bsp(vcpu))
2044                 kvm_lapic_set_base(vcpu,
2045                                 vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
2046         vcpu->arch.pv_eoi.msr_val = 0;
2047         apic_update_ppr(apic);
2048         if (vcpu->arch.apicv_active) {
2049                 kvm_x86_ops->apicv_post_state_restore(vcpu);
2050                 kvm_x86_ops->hwapic_irr_update(vcpu, -1);
2051                 kvm_x86_ops->hwapic_isr_update(vcpu, -1);
2052         }
2053
2054         vcpu->arch.apic_arb_prio = 0;
2055         vcpu->arch.apic_attention = 0;
2056
2057         apic_debug("%s: vcpu=%p, id=0x%x, base_msr="
2058                    "0x%016" PRIx64 ", base_address=0x%0lx.\n", __func__,
2059                    vcpu, kvm_lapic_get_reg(apic, APIC_ID),
2060                    vcpu->arch.apic_base, apic->base_address);
2061 }
2062
2063 /*
2064  *----------------------------------------------------------------------
2065  * timer interface
2066  *----------------------------------------------------------------------
2067  */
2068
2069 static bool lapic_is_periodic(struct kvm_lapic *apic)
2070 {
2071         return apic_lvtt_period(apic);
2072 }
2073
2074 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2075 {
2076         struct kvm_lapic *apic = vcpu->arch.apic;
2077
2078         if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2079                 return atomic_read(&apic->lapic_timer.pending);
2080
2081         return 0;
2082 }
2083
2084 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2085 {
2086         u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2087         int vector, mode, trig_mode;
2088
2089         if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2090                 vector = reg & APIC_VECTOR_MASK;
2091                 mode = reg & APIC_MODE_MASK;
2092                 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2093                 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2094                                         NULL);
2095         }
2096         return 0;
2097 }
2098
2099 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2100 {
2101         struct kvm_lapic *apic = vcpu->arch.apic;
2102
2103         if (apic)
2104                 kvm_apic_local_deliver(apic, APIC_LVT0);
2105 }
2106
2107 static const struct kvm_io_device_ops apic_mmio_ops = {
2108         .read     = apic_mmio_read,
2109         .write    = apic_mmio_write,
2110 };
2111
2112 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2113 {
2114         struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2115         struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2116
2117         apic_timer_expired(apic);
2118
2119         if (lapic_is_periodic(apic)) {
2120                 advance_periodic_target_expiration(apic);
2121                 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2122                 return HRTIMER_RESTART;
2123         } else
2124                 return HRTIMER_NORESTART;
2125 }
2126
2127 int kvm_create_lapic(struct kvm_vcpu *vcpu)
2128 {
2129         struct kvm_lapic *apic;
2130
2131         ASSERT(vcpu != NULL);
2132         apic_debug("apic_init %d\n", vcpu->vcpu_id);
2133
2134         apic = kzalloc(sizeof(*apic), GFP_KERNEL);
2135         if (!apic)
2136                 goto nomem;
2137
2138         vcpu->arch.apic = apic;
2139
2140         apic->regs = (void *)get_zeroed_page(GFP_KERNEL);
2141         if (!apic->regs) {
2142                 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2143                        vcpu->vcpu_id);
2144                 goto nomem_free_apic;
2145         }
2146         apic->vcpu = vcpu;
2147
2148         hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2149                      HRTIMER_MODE_ABS_PINNED);
2150         apic->lapic_timer.timer.function = apic_timer_fn;
2151
2152         /*
2153          * APIC is created enabled. This will prevent kvm_lapic_set_base from
2154          * thinking that APIC satet has changed.
2155          */
2156         vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2157         static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2158         kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2159
2160         return 0;
2161 nomem_free_apic:
2162         kfree(apic);
2163 nomem:
2164         return -ENOMEM;
2165 }
2166
2167 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2168 {
2169         struct kvm_lapic *apic = vcpu->arch.apic;
2170         u32 ppr;
2171
2172         if (!kvm_apic_hw_enabled(apic))
2173                 return -1;
2174
2175         __apic_update_ppr(apic, &ppr);
2176         return apic_has_interrupt_for_ppr(apic, ppr);
2177 }
2178
2179 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2180 {
2181         u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2182         int r = 0;
2183
2184         if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2185                 r = 1;
2186         if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2187             GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2188                 r = 1;
2189         return r;
2190 }
2191
2192 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2193 {
2194         struct kvm_lapic *apic = vcpu->arch.apic;
2195
2196         if (atomic_read(&apic->lapic_timer.pending) > 0) {
2197                 kvm_apic_local_deliver(apic, APIC_LVTT);
2198                 if (apic_lvtt_tscdeadline(apic))
2199                         apic->lapic_timer.tscdeadline = 0;
2200                 if (apic_lvtt_oneshot(apic)) {
2201                         apic->lapic_timer.tscdeadline = 0;
2202                         apic->lapic_timer.target_expiration = 0;
2203                 }
2204                 atomic_set(&apic->lapic_timer.pending, 0);
2205         }
2206 }
2207
2208 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2209 {
2210         int vector = kvm_apic_has_interrupt(vcpu);
2211         struct kvm_lapic *apic = vcpu->arch.apic;
2212         u32 ppr;
2213
2214         if (vector == -1)
2215                 return -1;
2216
2217         /*
2218          * We get here even with APIC virtualization enabled, if doing
2219          * nested virtualization and L1 runs with the "acknowledge interrupt
2220          * on exit" mode.  Then we cannot inject the interrupt via RVI,
2221          * because the process would deliver it through the IDT.
2222          */
2223
2224         apic_clear_irr(vector, apic);
2225         if (test_bit(vector, vcpu_to_synic(vcpu)->auto_eoi_bitmap)) {
2226                 /*
2227                  * For auto-EOI interrupts, there might be another pending
2228                  * interrupt above PPR, so check whether to raise another
2229                  * KVM_REQ_EVENT.
2230                  */
2231                 apic_update_ppr(apic);
2232         } else {
2233                 /*
2234                  * For normal interrupts, PPR has been raised and there cannot
2235                  * be a higher-priority pending interrupt---except if there was
2236                  * a concurrent interrupt injection, but that would have
2237                  * triggered KVM_REQ_EVENT already.
2238                  */
2239                 apic_set_isr(vector, apic);
2240                 __apic_update_ppr(apic, &ppr);
2241         }
2242
2243         return vector;
2244 }
2245
2246 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2247                 struct kvm_lapic_state *s, bool set)
2248 {
2249         if (apic_x2apic_mode(vcpu->arch.apic)) {
2250                 u32 *id = (u32 *)(s->regs + APIC_ID);
2251                 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2252
2253                 if (vcpu->kvm->arch.x2apic_format) {
2254                         if (*id != vcpu->vcpu_id)
2255                                 return -EINVAL;
2256                 } else {
2257                         if (set)
2258                                 *id >>= 24;
2259                         else
2260                                 *id <<= 24;
2261                 }
2262
2263                 /* In x2APIC mode, the LDR is fixed and based on the id */
2264                 if (set)
2265                         *ldr = kvm_apic_calc_x2apic_ldr(*id);
2266         }
2267
2268         return 0;
2269 }
2270
2271 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2272 {
2273         memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2274         return kvm_apic_state_fixup(vcpu, s, false);
2275 }
2276
2277 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2278 {
2279         struct kvm_lapic *apic = vcpu->arch.apic;
2280         int r;
2281
2282
2283         kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2284         /* set SPIV separately to get count of SW disabled APICs right */
2285         apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2286
2287         r = kvm_apic_state_fixup(vcpu, s, true);
2288         if (r)
2289                 return r;
2290         memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2291
2292         recalculate_apic_map(vcpu->kvm);
2293         kvm_apic_set_version(vcpu);
2294
2295         apic_update_ppr(apic);
2296         hrtimer_cancel(&apic->lapic_timer.timer);
2297         apic_update_lvtt(apic);
2298         apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2299         update_divide_count(apic);
2300         start_apic_timer(apic);
2301         apic->irr_pending = true;
2302         apic->isr_count = vcpu->arch.apicv_active ?
2303                                 1 : count_vectors(apic->regs + APIC_ISR);
2304         apic->highest_isr_cache = -1;
2305         if (vcpu->arch.apicv_active) {
2306                 kvm_x86_ops->apicv_post_state_restore(vcpu);
2307                 kvm_x86_ops->hwapic_irr_update(vcpu,
2308                                 apic_find_highest_irr(apic));
2309                 kvm_x86_ops->hwapic_isr_update(vcpu,
2310                                 apic_find_highest_isr(apic));
2311         }
2312         kvm_make_request(KVM_REQ_EVENT, vcpu);
2313         if (ioapic_in_kernel(vcpu->kvm))
2314                 kvm_rtc_eoi_tracking_restore_one(vcpu);
2315
2316         vcpu->arch.apic_arb_prio = 0;
2317
2318         return 0;
2319 }
2320
2321 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2322 {
2323         struct hrtimer *timer;
2324
2325         if (!lapic_in_kernel(vcpu))
2326                 return;
2327
2328         timer = &vcpu->arch.apic->lapic_timer.timer;
2329         if (hrtimer_cancel(timer))
2330                 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
2331 }
2332
2333 /*
2334  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2335  *
2336  * Detect whether guest triggered PV EOI since the
2337  * last entry. If yes, set EOI on guests's behalf.
2338  * Clear PV EOI in guest memory in any case.
2339  */
2340 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2341                                         struct kvm_lapic *apic)
2342 {
2343         bool pending;
2344         int vector;
2345         /*
2346          * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2347          * and KVM_PV_EOI_ENABLED in guest memory as follows:
2348          *
2349          * KVM_APIC_PV_EOI_PENDING is unset:
2350          *      -> host disabled PV EOI.
2351          * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2352          *      -> host enabled PV EOI, guest did not execute EOI yet.
2353          * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2354          *      -> host enabled PV EOI, guest executed EOI.
2355          */
2356         BUG_ON(!pv_eoi_enabled(vcpu));
2357         pending = pv_eoi_get_pending(vcpu);
2358         /*
2359          * Clear pending bit in any case: it will be set again on vmentry.
2360          * While this might not be ideal from performance point of view,
2361          * this makes sure pv eoi is only enabled when we know it's safe.
2362          */
2363         pv_eoi_clr_pending(vcpu);
2364         if (pending)
2365                 return;
2366         vector = apic_set_eoi(apic);
2367         trace_kvm_pv_eoi(apic, vector);
2368 }
2369
2370 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2371 {
2372         u32 data;
2373
2374         if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2375                 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2376
2377         if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2378                 return;
2379
2380         if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2381                                   sizeof(u32)))
2382                 return;
2383
2384         apic_set_tpr(vcpu->arch.apic, data & 0xff);
2385 }
2386
2387 /*
2388  * apic_sync_pv_eoi_to_guest - called before vmentry
2389  *
2390  * Detect whether it's safe to enable PV EOI and
2391  * if yes do so.
2392  */
2393 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2394                                         struct kvm_lapic *apic)
2395 {
2396         if (!pv_eoi_enabled(vcpu) ||
2397             /* IRR set or many bits in ISR: could be nested. */
2398             apic->irr_pending ||
2399             /* Cache not set: could be safe but we don't bother. */
2400             apic->highest_isr_cache == -1 ||
2401             /* Need EOI to update ioapic. */
2402             kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2403                 /*
2404                  * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2405                  * so we need not do anything here.
2406                  */
2407                 return;
2408         }
2409
2410         pv_eoi_set_pending(apic->vcpu);
2411 }
2412
2413 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2414 {
2415         u32 data, tpr;
2416         int max_irr, max_isr;
2417         struct kvm_lapic *apic = vcpu->arch.apic;
2418
2419         apic_sync_pv_eoi_to_guest(vcpu, apic);
2420
2421         if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2422                 return;
2423
2424         tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2425         max_irr = apic_find_highest_irr(apic);
2426         if (max_irr < 0)
2427                 max_irr = 0;
2428         max_isr = apic_find_highest_isr(apic);
2429         if (max_isr < 0)
2430                 max_isr = 0;
2431         data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2432
2433         kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2434                                 sizeof(u32));
2435 }
2436
2437 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2438 {
2439         if (vapic_addr) {
2440                 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2441                                         &vcpu->arch.apic->vapic_cache,
2442                                         vapic_addr, sizeof(u32)))
2443                         return -EINVAL;
2444                 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2445         } else {
2446                 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2447         }
2448
2449         vcpu->arch.apic->vapic_addr = vapic_addr;
2450         return 0;
2451 }
2452
2453 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2454 {
2455         struct kvm_lapic *apic = vcpu->arch.apic;
2456         u32 reg = (msr - APIC_BASE_MSR) << 4;
2457
2458         if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2459                 return 1;
2460
2461         if (reg == APIC_ICR2)
2462                 return 1;
2463
2464         /* if this is ICR write vector before command */
2465         if (reg == APIC_ICR)
2466                 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2467         return kvm_lapic_reg_write(apic, reg, (u32)data);
2468 }
2469
2470 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2471 {
2472         struct kvm_lapic *apic = vcpu->arch.apic;
2473         u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
2474
2475         if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2476                 return 1;
2477
2478         if (reg == APIC_DFR || reg == APIC_ICR2) {
2479                 apic_debug("KVM_APIC_READ: read x2apic reserved register %x\n",
2480                            reg);
2481                 return 1;
2482         }
2483
2484         if (kvm_lapic_reg_read(apic, reg, 4, &low))
2485                 return 1;
2486         if (reg == APIC_ICR)
2487                 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2488
2489         *data = (((u64)high) << 32) | low;
2490
2491         return 0;
2492 }
2493
2494 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2495 {
2496         struct kvm_lapic *apic = vcpu->arch.apic;
2497
2498         if (!lapic_in_kernel(vcpu))
2499                 return 1;
2500
2501         /* if this is ICR write vector before command */
2502         if (reg == APIC_ICR)
2503                 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2504         return kvm_lapic_reg_write(apic, reg, (u32)data);
2505 }
2506
2507 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2508 {
2509         struct kvm_lapic *apic = vcpu->arch.apic;
2510         u32 low, high = 0;
2511
2512         if (!lapic_in_kernel(vcpu))
2513                 return 1;
2514
2515         if (kvm_lapic_reg_read(apic, reg, 4, &low))
2516                 return 1;
2517         if (reg == APIC_ICR)
2518                 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2519
2520         *data = (((u64)high) << 32) | low;
2521
2522         return 0;
2523 }
2524
2525 int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data)
2526 {
2527         u64 addr = data & ~KVM_MSR_ENABLED;
2528         if (!IS_ALIGNED(addr, 4))
2529                 return 1;
2530
2531         vcpu->arch.pv_eoi.msr_val = data;
2532         if (!pv_eoi_enabled(vcpu))
2533                 return 0;
2534         return kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_eoi.data,
2535                                          addr, sizeof(u8));
2536 }
2537
2538 void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2539 {
2540         struct kvm_lapic *apic = vcpu->arch.apic;
2541         u8 sipi_vector;
2542         unsigned long pe;
2543
2544         if (!lapic_in_kernel(vcpu) || !apic->pending_events)
2545                 return;
2546
2547         /*
2548          * INITs are latched while in SMM.  Because an SMM CPU cannot
2549          * be in KVM_MP_STATE_INIT_RECEIVED state, just eat SIPIs
2550          * and delay processing of INIT until the next RSM.
2551          */
2552         if (is_smm(vcpu)) {
2553                 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2554                 if (test_bit(KVM_APIC_SIPI, &apic->pending_events))
2555                         clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2556                 return;
2557         }
2558
2559         pe = xchg(&apic->pending_events, 0);
2560         if (test_bit(KVM_APIC_INIT, &pe)) {
2561                 kvm_vcpu_reset(vcpu, true);
2562                 if (kvm_vcpu_is_bsp(apic->vcpu))
2563                         vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2564                 else
2565                         vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2566         }
2567         if (test_bit(KVM_APIC_SIPI, &pe) &&
2568             vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
2569                 /* evaluate pending_events before reading the vector */
2570                 smp_rmb();
2571                 sipi_vector = apic->sipi_vector;
2572                 apic_debug("vcpu %d received sipi with vector # %x\n",
2573                          vcpu->vcpu_id, sipi_vector);
2574                 kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
2575                 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2576         }
2577 }
2578
2579 void kvm_lapic_init(void)
2580 {
2581         /* do not patch jump label more than once per second */
2582         jump_label_rate_limit(&apic_hw_disabled, HZ);
2583         jump_label_rate_limit(&apic_sw_disabled, HZ);
2584 }
2585
2586 void kvm_lapic_exit(void)
2587 {
2588         static_key_deferred_flush(&apic_hw_disabled);
2589         static_key_deferred_flush(&apic_sw_disabled);
2590 }