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