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