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