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