1 // SPDX-License-Identifier: GPL-2.0-only
4 * Local APIC virtualization
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.
12 * Dor Laor <dor.laor@qumranet.com>
13 * Gregory Haskins <ghaskins@novell.com>
14 * Yaozu (Eddie) Dong <eddie.dong@intel.com>
16 * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
20 #include <linux/kvm_host.h>
21 #include <linux/kvm.h>
23 #include <linux/highmem.h>
24 #include <linux/smp.h>
25 #include <linux/hrtimer.h>
27 #include <linux/export.h>
28 #include <linux/math64.h>
29 #include <linux/slab.h>
30 #include <asm/processor.h>
34 #include <asm/current.h>
35 #include <asm/apicdef.h>
36 #include <asm/delay.h>
37 #include <linux/atomic.h>
38 #include <linux/jump_label.h>
39 #include "kvm_cache_regs.h"
49 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
51 #define mod_64(x, y) ((x) % (y))
59 /* 14 is the version for Xeon and Pentium 8.4.8*/
60 #define APIC_VERSION 0x14UL
61 #define LAPIC_MMIO_LENGTH (1 << 12)
62 /* followed define is not in apicdef.h */
63 #define MAX_APIC_VECTOR 256
64 #define APIC_VECTORS_PER_REG 32
66 static bool lapic_timer_advance_dynamic __read_mostly;
67 #define LAPIC_TIMER_ADVANCE_ADJUST_MIN 100 /* clock cycles */
68 #define LAPIC_TIMER_ADVANCE_ADJUST_MAX 10000 /* clock cycles */
69 #define LAPIC_TIMER_ADVANCE_NS_INIT 1000
70 #define LAPIC_TIMER_ADVANCE_NS_MAX 5000
71 /* step-by-step approximation to mitigate fluctuation */
72 #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
73 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data);
74 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
76 static inline void __kvm_lapic_set_reg(char *regs, int reg_off, u32 val)
78 *((u32 *) (regs + reg_off)) = val;
81 static inline void kvm_lapic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
83 __kvm_lapic_set_reg(apic->regs, reg_off, val);
86 static __always_inline u64 __kvm_lapic_get_reg64(char *regs, int reg)
88 BUILD_BUG_ON(reg != APIC_ICR);
89 return *((u64 *) (regs + reg));
92 static __always_inline u64 kvm_lapic_get_reg64(struct kvm_lapic *apic, int reg)
94 return __kvm_lapic_get_reg64(apic->regs, reg);
97 static __always_inline void __kvm_lapic_set_reg64(char *regs, int reg, u64 val)
99 BUILD_BUG_ON(reg != APIC_ICR);
100 *((u64 *) (regs + reg)) = val;
103 static __always_inline void kvm_lapic_set_reg64(struct kvm_lapic *apic,
106 __kvm_lapic_set_reg64(apic->regs, reg, val);
109 static inline int apic_test_vector(int vec, void *bitmap)
111 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
114 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
116 struct kvm_lapic *apic = vcpu->arch.apic;
118 return apic_test_vector(vector, apic->regs + APIC_ISR) ||
119 apic_test_vector(vector, apic->regs + APIC_IRR);
122 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
124 return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
127 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
129 return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
132 __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_hw_disabled, HZ);
133 __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_sw_disabled, HZ);
135 static inline int apic_enabled(struct kvm_lapic *apic)
137 return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
141 (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
144 (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
145 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
147 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
149 return apic->vcpu->vcpu_id;
152 static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
154 return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
155 (kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
158 bool kvm_can_use_hv_timer(struct kvm_vcpu *vcpu)
160 return kvm_x86_ops.set_hv_timer
161 && !(kvm_mwait_in_guest(vcpu->kvm) ||
162 kvm_can_post_timer_interrupt(vcpu));
165 static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
167 return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
170 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
172 return ((id >> 4) << 16) | (1 << (id & 0xf));
175 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
176 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
177 switch (map->logical_mode) {
178 case KVM_APIC_MODE_SW_DISABLED:
179 /* Arbitrarily use the flat map so that @cluster isn't NULL. */
180 *cluster = map->xapic_flat_map;
183 case KVM_APIC_MODE_X2APIC: {
184 u32 offset = (dest_id >> 16) * 16;
185 u32 max_apic_id = map->max_apic_id;
187 if (offset <= max_apic_id) {
188 u8 cluster_size = min(max_apic_id - offset + 1, 16U);
190 offset = array_index_nospec(offset, map->max_apic_id + 1);
191 *cluster = &map->phys_map[offset];
192 *mask = dest_id & (0xffff >> (16 - cluster_size));
199 case KVM_APIC_MODE_XAPIC_FLAT:
200 *cluster = map->xapic_flat_map;
201 *mask = dest_id & 0xff;
203 case KVM_APIC_MODE_XAPIC_CLUSTER:
204 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
205 *mask = dest_id & 0xf;
207 case KVM_APIC_MODE_MAP_DISABLED:
215 static void kvm_apic_map_free(struct rcu_head *rcu)
217 struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
222 static int kvm_recalculate_phys_map(struct kvm_apic_map *new,
223 struct kvm_vcpu *vcpu,
224 bool *xapic_id_mismatch)
226 struct kvm_lapic *apic = vcpu->arch.apic;
227 u32 x2apic_id = kvm_x2apic_id(apic);
228 u32 xapic_id = kvm_xapic_id(apic);
232 * For simplicity, KVM always allocates enough space for all possible
233 * xAPIC IDs. Yell, but don't kill the VM, as KVM can continue on
234 * without the optimized map.
236 if (WARN_ON_ONCE(xapic_id > new->max_apic_id))
240 * Bail if a vCPU was added and/or enabled its APIC between allocating
241 * the map and doing the actual calculations for the map. Note, KVM
242 * hardcodes the x2APIC ID to vcpu_id, i.e. there's no TOCTOU bug if
243 * the compiler decides to reload x2apic_id after this check.
245 if (x2apic_id > new->max_apic_id)
249 * Deliberately truncate the vCPU ID when detecting a mismatched APIC
250 * ID to avoid false positives if the vCPU ID, i.e. x2APIC ID, is a
251 * 32-bit value. Any unwanted aliasing due to truncation results will
254 if (!apic_x2apic_mode(apic) && xapic_id != (u8)vcpu->vcpu_id)
255 *xapic_id_mismatch = true;
258 * Apply KVM's hotplug hack if userspace has enable 32-bit APIC IDs.
259 * Allow sending events to vCPUs by their x2APIC ID even if the target
260 * vCPU is in legacy xAPIC mode, and silently ignore aliased xAPIC IDs
261 * (the x2APIC ID is truncated to 8 bits, causing IDs > 0xff to wrap
264 * Honor the architectural (and KVM's non-optimized) behavior if
265 * userspace has not enabled 32-bit x2APIC IDs. Each APIC is supposed
266 * to process messages independently. If multiple vCPUs have the same
267 * effective APIC ID, e.g. due to the x2APIC wrap or because the guest
268 * manually modified its xAPIC IDs, events targeting that ID are
269 * supposed to be recognized by all vCPUs with said ID.
271 if (vcpu->kvm->arch.x2apic_format) {
272 /* See also kvm_apic_match_physical_addr(). */
273 if (apic_x2apic_mode(apic) || x2apic_id > 0xff)
274 new->phys_map[x2apic_id] = apic;
276 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
277 new->phys_map[xapic_id] = apic;
280 * Disable the optimized map if the physical APIC ID is already
281 * mapped, i.e. is aliased to multiple vCPUs. The optimized
282 * map requires a strict 1:1 mapping between IDs and vCPUs.
284 if (apic_x2apic_mode(apic))
285 physical_id = x2apic_id;
287 physical_id = xapic_id;
289 if (new->phys_map[physical_id])
292 new->phys_map[physical_id] = apic;
298 static void kvm_recalculate_logical_map(struct kvm_apic_map *new,
299 struct kvm_vcpu *vcpu)
301 struct kvm_lapic *apic = vcpu->arch.apic;
302 enum kvm_apic_logical_mode logical_mode;
303 struct kvm_lapic **cluster;
307 if (new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
310 if (!kvm_apic_sw_enabled(apic))
313 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
317 if (apic_x2apic_mode(apic)) {
318 logical_mode = KVM_APIC_MODE_X2APIC;
320 ldr = GET_APIC_LOGICAL_ID(ldr);
321 if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
322 logical_mode = KVM_APIC_MODE_XAPIC_FLAT;
324 logical_mode = KVM_APIC_MODE_XAPIC_CLUSTER;
328 * To optimize logical mode delivery, all software-enabled APICs must
329 * be configured for the same mode.
331 if (new->logical_mode == KVM_APIC_MODE_SW_DISABLED) {
332 new->logical_mode = logical_mode;
333 } else if (new->logical_mode != logical_mode) {
334 new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
339 * In x2APIC mode, the LDR is read-only and derived directly from the
340 * x2APIC ID, thus is guaranteed to be addressable. KVM reuses
341 * kvm_apic_map.phys_map to optimize logical mode x2APIC interrupts by
342 * reversing the LDR calculation to get cluster of APICs, i.e. no
343 * additional work is required.
345 if (apic_x2apic_mode(apic)) {
346 WARN_ON_ONCE(ldr != kvm_apic_calc_x2apic_ldr(kvm_x2apic_id(apic)));
350 if (WARN_ON_ONCE(!kvm_apic_map_get_logical_dest(new, ldr,
352 new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
360 if (!is_power_of_2(mask) || cluster[ldr])
361 new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
367 * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
369 * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
370 * apic_map_lock_held.
378 void kvm_recalculate_apic_map(struct kvm *kvm)
380 struct kvm_apic_map *new, *old = NULL;
381 struct kvm_vcpu *vcpu;
383 u32 max_id = 255; /* enough space for any xAPIC ID */
384 bool xapic_id_mismatch = false;
386 /* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map. */
387 if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
390 WARN_ONCE(!irqchip_in_kernel(kvm),
391 "Dirty APIC map without an in-kernel local APIC");
393 mutex_lock(&kvm->arch.apic_map_lock);
395 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map
396 * (if clean) or the APIC registers (if dirty).
398 if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
399 DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
400 /* Someone else has updated the map. */
401 mutex_unlock(&kvm->arch.apic_map_lock);
405 kvm_for_each_vcpu(i, vcpu, kvm)
406 if (kvm_apic_present(vcpu))
407 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
409 new = kvzalloc(sizeof(struct kvm_apic_map) +
410 sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
416 new->max_apic_id = max_id;
417 new->logical_mode = KVM_APIC_MODE_SW_DISABLED;
419 kvm_for_each_vcpu(i, vcpu, kvm) {
420 if (!kvm_apic_present(vcpu))
423 if (kvm_recalculate_phys_map(new, vcpu, &xapic_id_mismatch)) {
429 kvm_recalculate_logical_map(new, vcpu);
433 * The optimized map is effectively KVM's internal version of APICv,
434 * and all unwanted aliasing that results in disabling the optimized
435 * map also applies to APICv.
438 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
440 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
442 if (!new || new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
443 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
445 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
447 if (xapic_id_mismatch)
448 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
450 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
452 old = rcu_dereference_protected(kvm->arch.apic_map,
453 lockdep_is_held(&kvm->arch.apic_map_lock));
454 rcu_assign_pointer(kvm->arch.apic_map, new);
456 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
457 * If another update has come in, leave it DIRTY.
459 atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
460 UPDATE_IN_PROGRESS, CLEAN);
461 mutex_unlock(&kvm->arch.apic_map_lock);
464 call_rcu(&old->rcu, kvm_apic_map_free);
466 kvm_make_scan_ioapic_request(kvm);
469 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
471 bool enabled = val & APIC_SPIV_APIC_ENABLED;
473 kvm_lapic_set_reg(apic, APIC_SPIV, val);
475 if (enabled != apic->sw_enabled) {
476 apic->sw_enabled = enabled;
478 static_branch_slow_dec_deferred(&apic_sw_disabled);
480 static_branch_inc(&apic_sw_disabled.key);
482 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
485 /* Check if there are APF page ready requests pending */
487 kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
490 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
492 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
493 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
496 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
498 kvm_lapic_set_reg(apic, APIC_LDR, id);
499 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
502 static inline void kvm_apic_set_dfr(struct kvm_lapic *apic, u32 val)
504 kvm_lapic_set_reg(apic, APIC_DFR, val);
505 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
508 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
510 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
512 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
514 kvm_lapic_set_reg(apic, APIC_ID, id);
515 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
516 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
519 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
521 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
524 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
526 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
529 static inline int apic_lvtt_period(struct kvm_lapic *apic)
531 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
534 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
536 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
539 static inline int apic_lvt_nmi_mode(u32 lvt_val)
541 return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
544 static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
546 return apic->nr_lvt_entries > lvt_index;
549 static inline int kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu *vcpu)
551 return KVM_APIC_MAX_NR_LVT_ENTRIES - !(vcpu->arch.mcg_cap & MCG_CMCI_P);
554 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
556 struct kvm_lapic *apic = vcpu->arch.apic;
559 if (!lapic_in_kernel(vcpu))
562 v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
565 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
566 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
567 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
568 * version first and level-triggered interrupts never get EOIed in
571 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) &&
572 !ioapic_in_kernel(vcpu->kvm))
573 v |= APIC_LVR_DIRECTED_EOI;
574 kvm_lapic_set_reg(apic, APIC_LVR, v);
577 void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu)
579 int nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
580 struct kvm_lapic *apic = vcpu->arch.apic;
583 if (!lapic_in_kernel(vcpu) || nr_lvt_entries == apic->nr_lvt_entries)
586 /* Initialize/mask any "new" LVT entries. */
587 for (i = apic->nr_lvt_entries; i < nr_lvt_entries; i++)
588 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
590 apic->nr_lvt_entries = nr_lvt_entries;
592 /* The number of LVT entries is reflected in the version register. */
593 kvm_apic_set_version(vcpu);
596 static const unsigned int apic_lvt_mask[KVM_APIC_MAX_NR_LVT_ENTRIES] = {
597 [LVT_TIMER] = LVT_MASK, /* timer mode mask added at runtime */
598 [LVT_THERMAL_MONITOR] = LVT_MASK | APIC_MODE_MASK,
599 [LVT_PERFORMANCE_COUNTER] = LVT_MASK | APIC_MODE_MASK,
600 [LVT_LINT0] = LINT_MASK,
601 [LVT_LINT1] = LINT_MASK,
602 [LVT_ERROR] = LVT_MASK,
603 [LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
606 static int find_highest_vector(void *bitmap)
611 for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
612 vec >= 0; vec -= APIC_VECTORS_PER_REG) {
613 reg = bitmap + REG_POS(vec);
615 return __fls(*reg) + vec;
621 static u8 count_vectors(void *bitmap)
627 for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
628 reg = bitmap + REG_POS(vec);
629 count += hweight32(*reg);
635 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
638 u32 pir_val, irr_val, prev_irr_val;
641 max_updated_irr = -1;
644 for (i = vec = 0; i <= 7; i++, vec += 32) {
645 pir_val = READ_ONCE(pir[i]);
646 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
648 prev_irr_val = irr_val;
649 irr_val |= xchg(&pir[i], 0);
650 *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
651 if (prev_irr_val != irr_val) {
653 __fls(irr_val ^ prev_irr_val) + vec;
657 *max_irr = __fls(irr_val) + vec;
660 return ((max_updated_irr != -1) &&
661 (max_updated_irr == *max_irr));
663 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
665 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
667 struct kvm_lapic *apic = vcpu->arch.apic;
669 return __kvm_apic_update_irr(pir, apic->regs, max_irr);
671 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
673 static inline int apic_search_irr(struct kvm_lapic *apic)
675 return find_highest_vector(apic->regs + APIC_IRR);
678 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
683 * Note that irr_pending is just a hint. It will be always
684 * true with virtual interrupt delivery enabled.
686 if (!apic->irr_pending)
689 result = apic_search_irr(apic);
690 ASSERT(result == -1 || result >= 16);
695 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
697 if (unlikely(apic->apicv_active)) {
698 /* need to update RVI */
699 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
700 static_call_cond(kvm_x86_hwapic_irr_update)(apic->vcpu,
701 apic_find_highest_irr(apic));
703 apic->irr_pending = false;
704 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
705 if (apic_search_irr(apic) != -1)
706 apic->irr_pending = true;
710 void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
712 apic_clear_irr(vec, vcpu->arch.apic);
714 EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
716 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
718 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
722 * With APIC virtualization enabled, all caching is disabled
723 * because the processor can modify ISR under the hood. Instead
726 if (unlikely(apic->apicv_active))
727 static_call_cond(kvm_x86_hwapic_isr_update)(vec);
730 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
732 * ISR (in service register) bit is set when injecting an interrupt.
733 * The highest vector is injected. Thus the latest bit set matches
734 * the highest bit in ISR.
736 apic->highest_isr_cache = vec;
740 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
745 * Note that isr_count is always 1, and highest_isr_cache
746 * is always -1, with APIC virtualization enabled.
748 if (!apic->isr_count)
750 if (likely(apic->highest_isr_cache != -1))
751 return apic->highest_isr_cache;
753 result = find_highest_vector(apic->regs + APIC_ISR);
754 ASSERT(result == -1 || result >= 16);
759 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
761 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
765 * We do get here for APIC virtualization enabled if the guest
766 * uses the Hyper-V APIC enlightenment. In this case we may need
767 * to trigger a new interrupt delivery by writing the SVI field;
768 * on the other hand isr_count and highest_isr_cache are unused
769 * and must be left alone.
771 if (unlikely(apic->apicv_active))
772 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
775 BUG_ON(apic->isr_count < 0);
776 apic->highest_isr_cache = -1;
780 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
782 /* This may race with setting of irr in __apic_accept_irq() and
783 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
784 * will cause vmexit immediately and the value will be recalculated
785 * on the next vmentry.
787 return apic_find_highest_irr(vcpu->arch.apic);
789 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
791 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
792 int vector, int level, int trig_mode,
793 struct dest_map *dest_map);
795 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
796 struct dest_map *dest_map)
798 struct kvm_lapic *apic = vcpu->arch.apic;
800 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
801 irq->level, irq->trig_mode, dest_map);
804 static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
805 struct kvm_lapic_irq *irq, u32 min)
808 struct kvm_vcpu *vcpu;
810 if (min > map->max_apic_id)
813 for_each_set_bit(i, ipi_bitmap,
814 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
815 if (map->phys_map[min + i]) {
816 vcpu = map->phys_map[min + i]->vcpu;
817 count += kvm_apic_set_irq(vcpu, irq, NULL);
824 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
825 unsigned long ipi_bitmap_high, u32 min,
826 unsigned long icr, int op_64_bit)
828 struct kvm_apic_map *map;
829 struct kvm_lapic_irq irq = {0};
830 int cluster_size = op_64_bit ? 64 : 32;
833 if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
836 irq.vector = icr & APIC_VECTOR_MASK;
837 irq.delivery_mode = icr & APIC_MODE_MASK;
838 irq.level = (icr & APIC_INT_ASSERT) != 0;
839 irq.trig_mode = icr & APIC_INT_LEVELTRIG;
842 map = rcu_dereference(kvm->arch.apic_map);
846 count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
848 count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
855 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
858 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
862 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
865 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
869 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
871 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
874 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
876 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
879 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
882 static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
886 if (pv_eoi_get_user(vcpu, &val) < 0)
889 val &= KVM_PV_EOI_ENABLED;
891 if (val && pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0)
895 * Clear pending bit in any case: it will be set again on vmentry.
896 * While this might not be ideal from performance point of view,
897 * this makes sure pv eoi is only enabled when we know it's safe.
899 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
904 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
907 if (kvm_x86_ops.sync_pir_to_irr)
908 highest_irr = static_call(kvm_x86_sync_pir_to_irr)(apic->vcpu);
910 highest_irr = apic_find_highest_irr(apic);
911 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
916 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
918 u32 tpr, isrv, ppr, old_ppr;
921 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
922 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
923 isr = apic_find_highest_isr(apic);
924 isrv = (isr != -1) ? isr : 0;
926 if ((tpr & 0xf0) >= (isrv & 0xf0))
933 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
935 return ppr < old_ppr;
938 static void apic_update_ppr(struct kvm_lapic *apic)
942 if (__apic_update_ppr(apic, &ppr) &&
943 apic_has_interrupt_for_ppr(apic, ppr) != -1)
944 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
947 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
949 apic_update_ppr(vcpu->arch.apic);
951 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
953 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
955 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
956 apic_update_ppr(apic);
959 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
961 return mda == (apic_x2apic_mode(apic) ?
962 X2APIC_BROADCAST : APIC_BROADCAST);
965 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
967 if (kvm_apic_broadcast(apic, mda))
971 * Hotplug hack: Accept interrupts for vCPUs in xAPIC mode as if they
972 * were in x2APIC mode if the target APIC ID can't be encoded as an
973 * xAPIC ID. This allows unique addressing of hotplugged vCPUs (which
974 * start in xAPIC mode) with an APIC ID that is unaddressable in xAPIC
975 * mode. Match the x2APIC ID if and only if the target APIC ID can't
976 * be encoded in xAPIC to avoid spurious matches against a vCPU that
977 * changed its (addressable) xAPIC ID (which is writable).
979 if (apic_x2apic_mode(apic) || mda > 0xff)
980 return mda == kvm_x2apic_id(apic);
982 return mda == kvm_xapic_id(apic);
985 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
989 if (kvm_apic_broadcast(apic, mda))
992 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
994 if (apic_x2apic_mode(apic))
995 return ((logical_id >> 16) == (mda >> 16))
996 && (logical_id & mda & 0xffff) != 0;
998 logical_id = GET_APIC_LOGICAL_ID(logical_id);
1000 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
1002 return (logical_id & mda) != 0;
1003 case APIC_DFR_CLUSTER:
1004 return ((logical_id >> 4) == (mda >> 4))
1005 && (logical_id & mda & 0xf) != 0;
1011 /* The KVM local APIC implementation has two quirks:
1013 * - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
1014 * in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
1015 * KVM doesn't do that aliasing.
1017 * - in-kernel IOAPIC messages have to be delivered directly to
1018 * x2APIC, because the kernel does not support interrupt remapping.
1019 * In order to support broadcast without interrupt remapping, x2APIC
1020 * rewrites the destination of non-IPI messages from APIC_BROADCAST
1021 * to X2APIC_BROADCAST.
1023 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API. This is
1024 * important when userspace wants to use x2APIC-format MSIs, because
1025 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
1027 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
1028 struct kvm_lapic *source, struct kvm_lapic *target)
1030 bool ipi = source != NULL;
1032 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
1033 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
1034 return X2APIC_BROADCAST;
1039 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
1040 int shorthand, unsigned int dest, int dest_mode)
1042 struct kvm_lapic *target = vcpu->arch.apic;
1043 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
1046 switch (shorthand) {
1047 case APIC_DEST_NOSHORT:
1048 if (dest_mode == APIC_DEST_PHYSICAL)
1049 return kvm_apic_match_physical_addr(target, mda);
1051 return kvm_apic_match_logical_addr(target, mda);
1052 case APIC_DEST_SELF:
1053 return target == source;
1054 case APIC_DEST_ALLINC:
1056 case APIC_DEST_ALLBUT:
1057 return target != source;
1062 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
1064 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
1065 const unsigned long *bitmap, u32 bitmap_size)
1070 mod = vector % dest_vcpus;
1072 for (i = 0; i <= mod; i++) {
1073 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
1074 BUG_ON(idx == bitmap_size);
1080 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
1082 if (!kvm->arch.disabled_lapic_found) {
1083 kvm->arch.disabled_lapic_found = true;
1084 pr_info("Disabled LAPIC found during irq injection\n");
1088 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
1089 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
1091 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
1092 if ((irq->dest_id == APIC_BROADCAST &&
1093 map->logical_mode != KVM_APIC_MODE_X2APIC))
1095 if (irq->dest_id == X2APIC_BROADCAST)
1098 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
1099 if (irq->dest_id == (x2apic_ipi ?
1100 X2APIC_BROADCAST : APIC_BROADCAST))
1107 /* Return true if the interrupt can be handled by using *bitmap as index mask
1108 * for valid destinations in *dst array.
1109 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
1110 * Note: we may have zero kvm_lapic destinations when we return true, which
1111 * means that the interrupt should be dropped. In this case, *bitmap would be
1112 * zero and *dst undefined.
1114 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
1115 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
1116 struct kvm_apic_map *map, struct kvm_lapic ***dst,
1117 unsigned long *bitmap)
1121 if (irq->shorthand == APIC_DEST_SELF && src) {
1125 } else if (irq->shorthand)
1128 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
1131 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
1132 if (irq->dest_id > map->max_apic_id) {
1135 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
1136 *dst = &map->phys_map[dest_id];
1143 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1147 if (!kvm_lowest_prio_delivery(irq))
1150 if (!kvm_vector_hashing_enabled()) {
1152 for_each_set_bit(i, bitmap, 16) {
1157 else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
1158 (*dst)[lowest]->vcpu) < 0)
1165 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
1168 if (!(*dst)[lowest]) {
1169 kvm_apic_disabled_lapic_found(kvm);
1175 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
1180 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
1181 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
1183 struct kvm_apic_map *map;
1184 unsigned long bitmap;
1185 struct kvm_lapic **dst = NULL;
1191 if (irq->shorthand == APIC_DEST_SELF) {
1192 if (KVM_BUG_ON(!src, kvm)) {
1196 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
1201 map = rcu_dereference(kvm->arch.apic_map);
1203 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
1206 for_each_set_bit(i, &bitmap, 16) {
1209 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
1218 * This routine tries to handle interrupts in posted mode, here is how
1219 * it deals with different cases:
1220 * - For single-destination interrupts, handle it in posted mode
1221 * - Else if vector hashing is enabled and it is a lowest-priority
1222 * interrupt, handle it in posted mode and use the following mechanism
1223 * to find the destination vCPU.
1224 * 1. For lowest-priority interrupts, store all the possible
1225 * destination vCPUs in an array.
1226 * 2. Use "guest vector % max number of destination vCPUs" to find
1227 * the right destination vCPU in the array for the lowest-priority
1229 * - Otherwise, use remapped mode to inject the interrupt.
1231 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
1232 struct kvm_vcpu **dest_vcpu)
1234 struct kvm_apic_map *map;
1235 unsigned long bitmap;
1236 struct kvm_lapic **dst = NULL;
1243 map = rcu_dereference(kvm->arch.apic_map);
1245 if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1246 hweight16(bitmap) == 1) {
1247 unsigned long i = find_first_bit(&bitmap, 16);
1250 *dest_vcpu = dst[i]->vcpu;
1260 * Add a pending IRQ into lapic.
1261 * Return 1 if successfully added and 0 if discarded.
1263 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1264 int vector, int level, int trig_mode,
1265 struct dest_map *dest_map)
1268 struct kvm_vcpu *vcpu = apic->vcpu;
1270 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1272 switch (delivery_mode) {
1273 case APIC_DM_LOWEST:
1274 vcpu->arch.apic_arb_prio++;
1277 if (unlikely(trig_mode && !level))
1280 /* FIXME add logic for vcpu on reset */
1281 if (unlikely(!apic_enabled(apic)))
1287 __set_bit(vcpu->vcpu_id, dest_map->map);
1288 dest_map->vectors[vcpu->vcpu_id] = vector;
1291 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1293 kvm_lapic_set_vector(vector,
1294 apic->regs + APIC_TMR);
1296 kvm_lapic_clear_vector(vector,
1297 apic->regs + APIC_TMR);
1300 static_call(kvm_x86_deliver_interrupt)(apic, delivery_mode,
1306 vcpu->arch.pv.pv_unhalted = 1;
1307 kvm_make_request(KVM_REQ_EVENT, vcpu);
1308 kvm_vcpu_kick(vcpu);
1312 if (!kvm_inject_smi(vcpu)) {
1313 kvm_vcpu_kick(vcpu);
1320 kvm_inject_nmi(vcpu);
1321 kvm_vcpu_kick(vcpu);
1325 if (!trig_mode || level) {
1327 /* assumes that there are only KVM_APIC_INIT/SIPI */
1328 apic->pending_events = (1UL << KVM_APIC_INIT);
1329 kvm_make_request(KVM_REQ_EVENT, vcpu);
1330 kvm_vcpu_kick(vcpu);
1334 case APIC_DM_STARTUP:
1336 apic->sipi_vector = vector;
1337 /* make sure sipi_vector is visible for the receiver */
1339 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1340 kvm_make_request(KVM_REQ_EVENT, vcpu);
1341 kvm_vcpu_kick(vcpu);
1344 case APIC_DM_EXTINT:
1346 * Should only be called by kvm_apic_local_deliver() with LVT0,
1347 * before NMI watchdog was enabled. Already handled by
1348 * kvm_apic_accept_pic_intr().
1353 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1361 * This routine identifies the destination vcpus mask meant to receive the
1362 * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
1363 * out the destination vcpus array and set the bitmap or it traverses to
1364 * each available vcpu to identify the same.
1366 void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
1367 unsigned long *vcpu_bitmap)
1369 struct kvm_lapic **dest_vcpu = NULL;
1370 struct kvm_lapic *src = NULL;
1371 struct kvm_apic_map *map;
1372 struct kvm_vcpu *vcpu;
1373 unsigned long bitmap, i;
1378 map = rcu_dereference(kvm->arch.apic_map);
1380 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
1383 for_each_set_bit(i, &bitmap, 16) {
1386 vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
1387 __set_bit(vcpu_idx, vcpu_bitmap);
1390 kvm_for_each_vcpu(i, vcpu, kvm) {
1391 if (!kvm_apic_present(vcpu))
1393 if (!kvm_apic_match_dest(vcpu, NULL,
1398 __set_bit(i, vcpu_bitmap);
1404 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1406 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1409 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1411 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1414 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1418 /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1419 if (!kvm_ioapic_handles_vector(apic, vector))
1422 /* Request a KVM exit to inform the userspace IOAPIC. */
1423 if (irqchip_split(apic->vcpu->kvm)) {
1424 apic->vcpu->arch.pending_ioapic_eoi = vector;
1425 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1429 if (apic_test_vector(vector, apic->regs + APIC_TMR))
1430 trigger_mode = IOAPIC_LEVEL_TRIG;
1432 trigger_mode = IOAPIC_EDGE_TRIG;
1434 kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1437 static int apic_set_eoi(struct kvm_lapic *apic)
1439 int vector = apic_find_highest_isr(apic);
1441 trace_kvm_eoi(apic, vector);
1444 * Not every write EOI will has corresponding ISR,
1445 * one example is when Kernel check timer on setup_IO_APIC
1450 apic_clear_isr(vector, apic);
1451 apic_update_ppr(apic);
1453 if (to_hv_vcpu(apic->vcpu) &&
1454 test_bit(vector, to_hv_synic(apic->vcpu)->vec_bitmap))
1455 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1457 kvm_ioapic_send_eoi(apic, vector);
1458 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1463 * this interface assumes a trap-like exit, which has already finished
1464 * desired side effect including vISR and vPPR update.
1466 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1468 struct kvm_lapic *apic = vcpu->arch.apic;
1470 trace_kvm_eoi(apic, vector);
1472 kvm_ioapic_send_eoi(apic, vector);
1473 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1475 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1477 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1479 struct kvm_lapic_irq irq;
1481 /* KVM has no delay and should always clear the BUSY/PENDING flag. */
1482 WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1484 irq.vector = icr_low & APIC_VECTOR_MASK;
1485 irq.delivery_mode = icr_low & APIC_MODE_MASK;
1486 irq.dest_mode = icr_low & APIC_DEST_MASK;
1487 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1488 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1489 irq.shorthand = icr_low & APIC_SHORT_MASK;
1490 irq.msi_redir_hint = false;
1491 if (apic_x2apic_mode(apic))
1492 irq.dest_id = icr_high;
1494 irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
1496 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1498 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1500 EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1502 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1504 ktime_t remaining, now;
1507 ASSERT(apic != NULL);
1509 /* if initial count is 0, current count should also be 0 */
1510 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1511 apic->lapic_timer.period == 0)
1515 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1516 if (ktime_to_ns(remaining) < 0)
1519 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1520 return div64_u64(ns, (APIC_BUS_CYCLE_NS * apic->divide_count));
1523 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1525 struct kvm_vcpu *vcpu = apic->vcpu;
1526 struct kvm_run *run = vcpu->run;
1528 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1529 run->tpr_access.rip = kvm_rip_read(vcpu);
1530 run->tpr_access.is_write = write;
1533 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1535 if (apic->vcpu->arch.tpr_access_reporting)
1536 __report_tpr_access(apic, write);
1539 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1543 if (offset >= LAPIC_MMIO_LENGTH)
1550 case APIC_TMCCT: /* Timer CCR */
1551 if (apic_lvtt_tscdeadline(apic))
1554 val = apic_get_tmcct(apic);
1557 apic_update_ppr(apic);
1558 val = kvm_lapic_get_reg(apic, offset);
1561 report_tpr_access(apic, false);
1564 val = kvm_lapic_get_reg(apic, offset);
1571 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1573 return container_of(dev, struct kvm_lapic, dev);
1576 #define APIC_REG_MASK(reg) (1ull << ((reg) >> 4))
1577 #define APIC_REGS_MASK(first, count) \
1578 (APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1580 u64 kvm_lapic_readable_reg_mask(struct kvm_lapic *apic)
1582 /* Leave bits '0' for reserved and write-only registers. */
1583 u64 valid_reg_mask =
1584 APIC_REG_MASK(APIC_ID) |
1585 APIC_REG_MASK(APIC_LVR) |
1586 APIC_REG_MASK(APIC_TASKPRI) |
1587 APIC_REG_MASK(APIC_PROCPRI) |
1588 APIC_REG_MASK(APIC_LDR) |
1589 APIC_REG_MASK(APIC_SPIV) |
1590 APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1591 APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1592 APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1593 APIC_REG_MASK(APIC_ESR) |
1594 APIC_REG_MASK(APIC_ICR) |
1595 APIC_REG_MASK(APIC_LVTT) |
1596 APIC_REG_MASK(APIC_LVTTHMR) |
1597 APIC_REG_MASK(APIC_LVTPC) |
1598 APIC_REG_MASK(APIC_LVT0) |
1599 APIC_REG_MASK(APIC_LVT1) |
1600 APIC_REG_MASK(APIC_LVTERR) |
1601 APIC_REG_MASK(APIC_TMICT) |
1602 APIC_REG_MASK(APIC_TMCCT) |
1603 APIC_REG_MASK(APIC_TDCR);
1605 if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
1606 valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
1608 /* ARBPRI, DFR, and ICR2 are not valid in x2APIC mode. */
1609 if (!apic_x2apic_mode(apic))
1610 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1611 APIC_REG_MASK(APIC_DFR) |
1612 APIC_REG_MASK(APIC_ICR2);
1614 return valid_reg_mask;
1616 EXPORT_SYMBOL_GPL(kvm_lapic_readable_reg_mask);
1618 static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1621 unsigned char alignment = offset & 0xf;
1625 * WARN if KVM reads ICR in x2APIC mode, as it's an 8-byte register in
1626 * x2APIC and needs to be manually handled by the caller.
1628 WARN_ON_ONCE(apic_x2apic_mode(apic) && offset == APIC_ICR);
1630 if (alignment + len > 4)
1633 if (offset > 0x3f0 ||
1634 !(kvm_lapic_readable_reg_mask(apic) & APIC_REG_MASK(offset)))
1637 result = __apic_read(apic, offset & ~0xf);
1639 trace_kvm_apic_read(offset, result);
1645 memcpy(data, (char *)&result + alignment, len);
1648 printk(KERN_ERR "Local APIC read with len = %x, "
1649 "should be 1,2, or 4 instead\n", len);
1655 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1657 return addr >= apic->base_address &&
1658 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1661 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1662 gpa_t address, int len, void *data)
1664 struct kvm_lapic *apic = to_lapic(this);
1665 u32 offset = address - apic->base_address;
1667 if (!apic_mmio_in_range(apic, address))
1670 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1671 if (!kvm_check_has_quirk(vcpu->kvm,
1672 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1675 memset(data, 0xff, len);
1679 kvm_lapic_reg_read(apic, offset, len, data);
1684 static void update_divide_count(struct kvm_lapic *apic)
1686 u32 tmp1, tmp2, tdcr;
1688 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1690 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1691 apic->divide_count = 0x1 << (tmp2 & 0x7);
1694 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1697 * Do not allow the guest to program periodic timers with small
1698 * interval, since the hrtimers are not throttled by the host
1701 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1702 s64 min_period = min_timer_period_us * 1000LL;
1704 if (apic->lapic_timer.period < min_period) {
1705 pr_info_ratelimited(
1706 "vcpu %i: requested %lld ns "
1707 "lapic timer period limited to %lld ns\n",
1708 apic->vcpu->vcpu_id,
1709 apic->lapic_timer.period, min_period);
1710 apic->lapic_timer.period = min_period;
1715 static void cancel_hv_timer(struct kvm_lapic *apic);
1717 static void cancel_apic_timer(struct kvm_lapic *apic)
1719 hrtimer_cancel(&apic->lapic_timer.timer);
1721 if (apic->lapic_timer.hv_timer_in_use)
1722 cancel_hv_timer(apic);
1724 atomic_set(&apic->lapic_timer.pending, 0);
1727 static void apic_update_lvtt(struct kvm_lapic *apic)
1729 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1730 apic->lapic_timer.timer_mode_mask;
1732 if (apic->lapic_timer.timer_mode != timer_mode) {
1733 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1734 APIC_LVT_TIMER_TSCDEADLINE)) {
1735 cancel_apic_timer(apic);
1736 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1737 apic->lapic_timer.period = 0;
1738 apic->lapic_timer.tscdeadline = 0;
1740 apic->lapic_timer.timer_mode = timer_mode;
1741 limit_periodic_timer_frequency(apic);
1746 * On APICv, this test will cause a busy wait
1747 * during a higher-priority task.
1750 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1752 struct kvm_lapic *apic = vcpu->arch.apic;
1753 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1755 if (kvm_apic_hw_enabled(apic)) {
1756 int vec = reg & APIC_VECTOR_MASK;
1757 void *bitmap = apic->regs + APIC_ISR;
1759 if (apic->apicv_active)
1760 bitmap = apic->regs + APIC_IRR;
1762 if (apic_test_vector(vec, bitmap))
1768 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1770 u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1773 * If the guest TSC is running at a different ratio than the host, then
1774 * convert the delay to nanoseconds to achieve an accurate delay. Note
1775 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1776 * always for VMX enabled hardware.
1778 if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1779 __delay(min(guest_cycles,
1780 nsec_to_cycles(vcpu, timer_advance_ns)));
1782 u64 delay_ns = guest_cycles * 1000000ULL;
1783 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1784 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1788 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1789 s64 advance_expire_delta)
1791 struct kvm_lapic *apic = vcpu->arch.apic;
1792 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1795 /* Do not adjust for tiny fluctuations or large random spikes. */
1796 if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1797 abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1801 if (advance_expire_delta < 0) {
1802 ns = -advance_expire_delta * 1000000ULL;
1803 do_div(ns, vcpu->arch.virtual_tsc_khz);
1804 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1807 ns = advance_expire_delta * 1000000ULL;
1808 do_div(ns, vcpu->arch.virtual_tsc_khz);
1809 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1812 if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1813 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1814 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1817 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1819 struct kvm_lapic *apic = vcpu->arch.apic;
1820 u64 guest_tsc, tsc_deadline;
1822 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1823 apic->lapic_timer.expired_tscdeadline = 0;
1824 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1825 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1827 if (lapic_timer_advance_dynamic) {
1828 adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
1830 * If the timer fired early, reread the TSC to account for the
1831 * overhead of the above adjustment to avoid waiting longer
1832 * than is necessary.
1834 if (guest_tsc < tsc_deadline)
1835 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1838 if (guest_tsc < tsc_deadline)
1839 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1842 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1844 if (lapic_in_kernel(vcpu) &&
1845 vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1846 vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1847 lapic_timer_int_injected(vcpu))
1848 __kvm_wait_lapic_expire(vcpu);
1850 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1852 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1854 struct kvm_timer *ktimer = &apic->lapic_timer;
1856 kvm_apic_local_deliver(apic, APIC_LVTT);
1857 if (apic_lvtt_tscdeadline(apic)) {
1858 ktimer->tscdeadline = 0;
1859 } else if (apic_lvtt_oneshot(apic)) {
1860 ktimer->tscdeadline = 0;
1861 ktimer->target_expiration = 0;
1865 static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
1867 struct kvm_vcpu *vcpu = apic->vcpu;
1868 struct kvm_timer *ktimer = &apic->lapic_timer;
1870 if (atomic_read(&apic->lapic_timer.pending))
1873 if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1874 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1876 if (!from_timer_fn && apic->apicv_active) {
1877 WARN_ON(kvm_get_running_vcpu() != vcpu);
1878 kvm_apic_inject_pending_timer_irqs(apic);
1882 if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1884 * Ensure the guest's timer has truly expired before posting an
1885 * interrupt. Open code the relevant checks to avoid querying
1886 * lapic_timer_int_injected(), which will be false since the
1887 * interrupt isn't yet injected. Waiting until after injecting
1888 * is not an option since that won't help a posted interrupt.
1890 if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1891 vcpu->arch.apic->lapic_timer.timer_advance_ns)
1892 __kvm_wait_lapic_expire(vcpu);
1893 kvm_apic_inject_pending_timer_irqs(apic);
1897 atomic_inc(&apic->lapic_timer.pending);
1898 kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1900 kvm_vcpu_kick(vcpu);
1903 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1905 struct kvm_timer *ktimer = &apic->lapic_timer;
1906 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1909 struct kvm_vcpu *vcpu = apic->vcpu;
1910 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1911 unsigned long flags;
1914 if (unlikely(!tscdeadline || !this_tsc_khz))
1917 local_irq_save(flags);
1920 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1922 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1923 do_div(ns, this_tsc_khz);
1925 if (likely(tscdeadline > guest_tsc) &&
1926 likely(ns > apic->lapic_timer.timer_advance_ns)) {
1927 expire = ktime_add_ns(now, ns);
1928 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1929 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1931 apic_timer_expired(apic, false);
1933 local_irq_restore(flags);
1936 static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1938 return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
1941 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1943 ktime_t now, remaining;
1944 u64 ns_remaining_old, ns_remaining_new;
1946 apic->lapic_timer.period =
1947 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1948 limit_periodic_timer_frequency(apic);
1951 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1952 if (ktime_to_ns(remaining) < 0)
1955 ns_remaining_old = ktime_to_ns(remaining);
1956 ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1957 apic->divide_count, old_divisor);
1959 apic->lapic_timer.tscdeadline +=
1960 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1961 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1962 apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1965 static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1972 apic->lapic_timer.period =
1973 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1975 if (!apic->lapic_timer.period) {
1976 apic->lapic_timer.tscdeadline = 0;
1980 limit_periodic_timer_frequency(apic);
1981 deadline = apic->lapic_timer.period;
1983 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1984 if (unlikely(count_reg != APIC_TMICT)) {
1985 deadline = tmict_to_ns(apic,
1986 kvm_lapic_get_reg(apic, count_reg));
1987 if (unlikely(deadline <= 0)) {
1988 if (apic_lvtt_period(apic))
1989 deadline = apic->lapic_timer.period;
1993 else if (unlikely(deadline > apic->lapic_timer.period)) {
1994 pr_info_ratelimited(
1995 "vcpu %i: requested lapic timer restore with "
1996 "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
1997 "Using initial count to start timer.\n",
1998 apic->vcpu->vcpu_id,
2000 kvm_lapic_get_reg(apic, count_reg),
2001 deadline, apic->lapic_timer.period);
2002 kvm_lapic_set_reg(apic, count_reg, 0);
2003 deadline = apic->lapic_timer.period;
2008 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2009 nsec_to_cycles(apic->vcpu, deadline);
2010 apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
2015 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
2017 ktime_t now = ktime_get();
2022 * Synchronize both deadlines to the same time source or
2023 * differences in the periods (caused by differences in the
2024 * underlying clocks or numerical approximation errors) will
2025 * cause the two to drift apart over time as the errors
2028 apic->lapic_timer.target_expiration =
2029 ktime_add_ns(apic->lapic_timer.target_expiration,
2030 apic->lapic_timer.period);
2031 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
2032 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2033 nsec_to_cycles(apic->vcpu, delta);
2036 static void start_sw_period(struct kvm_lapic *apic)
2038 if (!apic->lapic_timer.period)
2041 if (ktime_after(ktime_get(),
2042 apic->lapic_timer.target_expiration)) {
2043 apic_timer_expired(apic, false);
2045 if (apic_lvtt_oneshot(apic))
2048 advance_periodic_target_expiration(apic);
2051 hrtimer_start(&apic->lapic_timer.timer,
2052 apic->lapic_timer.target_expiration,
2053 HRTIMER_MODE_ABS_HARD);
2056 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2058 if (!lapic_in_kernel(vcpu))
2061 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2064 static void cancel_hv_timer(struct kvm_lapic *apic)
2066 WARN_ON(preemptible());
2067 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2068 static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
2069 apic->lapic_timer.hv_timer_in_use = false;
2072 static bool start_hv_timer(struct kvm_lapic *apic)
2074 struct kvm_timer *ktimer = &apic->lapic_timer;
2075 struct kvm_vcpu *vcpu = apic->vcpu;
2078 WARN_ON(preemptible());
2079 if (!kvm_can_use_hv_timer(vcpu))
2082 if (!ktimer->tscdeadline)
2085 if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
2088 ktimer->hv_timer_in_use = true;
2089 hrtimer_cancel(&ktimer->timer);
2092 * To simplify handling the periodic timer, leave the hv timer running
2093 * even if the deadline timer has expired, i.e. rely on the resulting
2094 * VM-Exit to recompute the periodic timer's target expiration.
2096 if (!apic_lvtt_period(apic)) {
2098 * Cancel the hv timer if the sw timer fired while the hv timer
2099 * was being programmed, or if the hv timer itself expired.
2101 if (atomic_read(&ktimer->pending)) {
2102 cancel_hv_timer(apic);
2103 } else if (expired) {
2104 apic_timer_expired(apic, false);
2105 cancel_hv_timer(apic);
2109 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
2114 static void start_sw_timer(struct kvm_lapic *apic)
2116 struct kvm_timer *ktimer = &apic->lapic_timer;
2118 WARN_ON(preemptible());
2119 if (apic->lapic_timer.hv_timer_in_use)
2120 cancel_hv_timer(apic);
2121 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
2124 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2125 start_sw_period(apic);
2126 else if (apic_lvtt_tscdeadline(apic))
2127 start_sw_tscdeadline(apic);
2128 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
2131 static void restart_apic_timer(struct kvm_lapic *apic)
2135 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
2138 if (!start_hv_timer(apic))
2139 start_sw_timer(apic);
2144 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
2146 struct kvm_lapic *apic = vcpu->arch.apic;
2149 /* If the preempt notifier has already run, it also called apic_timer_expired */
2150 if (!apic->lapic_timer.hv_timer_in_use)
2152 WARN_ON(kvm_vcpu_is_blocking(vcpu));
2153 apic_timer_expired(apic, false);
2154 cancel_hv_timer(apic);
2156 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
2157 advance_periodic_target_expiration(apic);
2158 restart_apic_timer(apic);
2163 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
2165 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2167 restart_apic_timer(vcpu->arch.apic);
2170 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2172 struct kvm_lapic *apic = vcpu->arch.apic;
2175 /* Possibly the TSC deadline timer is not enabled yet */
2176 if (apic->lapic_timer.hv_timer_in_use)
2177 start_sw_timer(apic);
2181 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2183 struct kvm_lapic *apic = vcpu->arch.apic;
2185 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2186 restart_apic_timer(apic);
2189 static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2191 atomic_set(&apic->lapic_timer.pending, 0);
2193 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2194 && !set_target_expiration(apic, count_reg))
2197 restart_apic_timer(apic);
2200 static void start_apic_timer(struct kvm_lapic *apic)
2202 __start_apic_timer(apic, APIC_TMICT);
2205 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2207 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2209 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
2210 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
2211 if (lvt0_in_nmi_mode) {
2212 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2214 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2218 static int get_lvt_index(u32 reg)
2220 if (reg == APIC_LVTCMCI)
2222 if (reg < APIC_LVTT || reg > APIC_LVTERR)
2224 return array_index_nospec(
2225 (reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
2228 static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2232 trace_kvm_apic_write(reg, val);
2235 case APIC_ID: /* Local APIC ID */
2236 if (!apic_x2apic_mode(apic)) {
2237 kvm_apic_set_xapic_id(apic, val >> 24);
2244 report_tpr_access(apic, true);
2245 apic_set_tpr(apic, val & 0xff);
2253 if (!apic_x2apic_mode(apic))
2254 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
2260 if (!apic_x2apic_mode(apic))
2261 kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2268 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2269 mask |= APIC_SPIV_DIRECTED_EOI;
2270 apic_set_spiv(apic, val & mask);
2271 if (!(val & APIC_SPIV_APIC_ENABLED)) {
2274 for (i = 0; i < apic->nr_lvt_entries; i++) {
2275 kvm_lapic_set_reg(apic, APIC_LVTx(i),
2276 kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2278 apic_update_lvtt(apic);
2279 atomic_set(&apic->lapic_timer.pending, 0);
2285 WARN_ON_ONCE(apic_x2apic_mode(apic));
2287 /* No delay here, so we always clear the pending bit */
2288 val &= ~APIC_ICR_BUSY;
2289 kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2290 kvm_lapic_set_reg(apic, APIC_ICR, val);
2293 if (apic_x2apic_mode(apic))
2296 kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2300 apic_manage_nmi_watchdog(apic, val);
2306 case APIC_LVTCMCI: {
2307 u32 index = get_lvt_index(reg);
2308 if (!kvm_lapic_lvt_supported(apic, index)) {
2312 if (!kvm_apic_sw_enabled(apic))
2313 val |= APIC_LVT_MASKED;
2314 val &= apic_lvt_mask[index];
2315 kvm_lapic_set_reg(apic, reg, val);
2320 if (!kvm_apic_sw_enabled(apic))
2321 val |= APIC_LVT_MASKED;
2322 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
2323 kvm_lapic_set_reg(apic, APIC_LVTT, val);
2324 apic_update_lvtt(apic);
2328 if (apic_lvtt_tscdeadline(apic))
2331 cancel_apic_timer(apic);
2332 kvm_lapic_set_reg(apic, APIC_TMICT, val);
2333 start_apic_timer(apic);
2337 uint32_t old_divisor = apic->divide_count;
2339 kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2340 update_divide_count(apic);
2341 if (apic->divide_count != old_divisor &&
2342 apic->lapic_timer.period) {
2343 hrtimer_cancel(&apic->lapic_timer.timer);
2344 update_target_expiration(apic, old_divisor);
2345 restart_apic_timer(apic);
2350 if (apic_x2apic_mode(apic) && val != 0)
2356 * Self-IPI exists only when x2APIC is enabled. Bits 7:0 hold
2357 * the vector, everything else is reserved.
2359 if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
2362 kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
2370 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2371 * was toggled, the APIC ID changed, etc... The maps are marked dirty
2372 * on relevant changes, i.e. this is a nop for most writes.
2374 kvm_recalculate_apic_map(apic->vcpu->kvm);
2379 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2380 gpa_t address, int len, const void *data)
2382 struct kvm_lapic *apic = to_lapic(this);
2383 unsigned int offset = address - apic->base_address;
2386 if (!apic_mmio_in_range(apic, address))
2389 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2390 if (!kvm_check_has_quirk(vcpu->kvm,
2391 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2398 * APIC register must be aligned on 128-bits boundary.
2399 * 32/64/128 bits registers must be accessed thru 32 bits.
2402 if (len != 4 || (offset & 0xf))
2407 kvm_lapic_reg_write(apic, offset & 0xff0, val);
2412 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2414 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2416 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2418 /* emulate APIC access in a trap manner */
2419 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2421 struct kvm_lapic *apic = vcpu->arch.apic;
2425 * ICR is a single 64-bit register when x2APIC is enabled. For legacy
2426 * xAPIC, ICR writes need to go down the common (slightly slower) path
2427 * to get the upper half from ICR2.
2429 if (apic_x2apic_mode(apic) && offset == APIC_ICR) {
2430 val = kvm_lapic_get_reg64(apic, APIC_ICR);
2431 kvm_apic_send_ipi(apic, (u32)val, (u32)(val >> 32));
2432 trace_kvm_apic_write(APIC_ICR, val);
2434 /* TODO: optimize to just emulate side effect w/o one more write */
2435 val = kvm_lapic_get_reg(apic, offset);
2436 kvm_lapic_reg_write(apic, offset, (u32)val);
2439 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2441 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2443 struct kvm_lapic *apic = vcpu->arch.apic;
2445 if (!vcpu->arch.apic)
2448 hrtimer_cancel(&apic->lapic_timer.timer);
2450 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2451 static_branch_slow_dec_deferred(&apic_hw_disabled);
2453 if (!apic->sw_enabled)
2454 static_branch_slow_dec_deferred(&apic_sw_disabled);
2457 free_page((unsigned long)apic->regs);
2463 *----------------------------------------------------------------------
2465 *----------------------------------------------------------------------
2467 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2469 struct kvm_lapic *apic = vcpu->arch.apic;
2471 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2474 return apic->lapic_timer.tscdeadline;
2477 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2479 struct kvm_lapic *apic = vcpu->arch.apic;
2481 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2484 hrtimer_cancel(&apic->lapic_timer.timer);
2485 apic->lapic_timer.tscdeadline = data;
2486 start_apic_timer(apic);
2489 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2491 apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2494 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2498 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2500 return (tpr & 0xf0) >> 4;
2503 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2505 u64 old_value = vcpu->arch.apic_base;
2506 struct kvm_lapic *apic = vcpu->arch.apic;
2508 vcpu->arch.apic_base = value;
2510 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2511 kvm_update_cpuid_runtime(vcpu);
2516 /* update jump label if enable bit changes */
2517 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2518 if (value & MSR_IA32_APICBASE_ENABLE) {
2519 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2520 static_branch_slow_dec_deferred(&apic_hw_disabled);
2521 /* Check if there are APF page ready requests pending */
2522 kvm_make_request(KVM_REQ_APF_READY, vcpu);
2524 static_branch_inc(&apic_hw_disabled.key);
2525 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2529 if ((old_value ^ value) & X2APIC_ENABLE) {
2530 if (value & X2APIC_ENABLE)
2531 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2532 else if (value & MSR_IA32_APICBASE_ENABLE)
2533 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2536 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
2537 kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
2538 static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
2541 apic->base_address = apic->vcpu->arch.apic_base &
2542 MSR_IA32_APICBASE_BASE;
2544 if ((value & MSR_IA32_APICBASE_ENABLE) &&
2545 apic->base_address != APIC_DEFAULT_PHYS_BASE) {
2546 kvm_set_apicv_inhibit(apic->vcpu->kvm,
2547 APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
2551 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2553 struct kvm_lapic *apic = vcpu->arch.apic;
2555 if (apic->apicv_active) {
2556 /* irr_pending is always true when apicv is activated. */
2557 apic->irr_pending = true;
2558 apic->isr_count = 1;
2561 * Don't clear irr_pending, searching the IRR can race with
2562 * updates from the CPU as APICv is still active from hardware's
2563 * perspective. The flag will be cleared as appropriate when
2564 * KVM injects the interrupt.
2566 apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2568 apic->highest_isr_cache = -1;
2571 int kvm_alloc_apic_access_page(struct kvm *kvm)
2577 mutex_lock(&kvm->slots_lock);
2578 if (kvm->arch.apic_access_memslot_enabled ||
2579 kvm->arch.apic_access_memslot_inhibited)
2582 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
2583 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
2589 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
2590 if (is_error_page(page)) {
2596 * Do not pin the page in memory, so that memory hot-unplug
2597 * is able to migrate it.
2600 kvm->arch.apic_access_memslot_enabled = true;
2602 mutex_unlock(&kvm->slots_lock);
2605 EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2607 void kvm_inhibit_apic_access_page(struct kvm_vcpu *vcpu)
2609 struct kvm *kvm = vcpu->kvm;
2611 if (!kvm->arch.apic_access_memslot_enabled)
2614 kvm_vcpu_srcu_read_unlock(vcpu);
2616 mutex_lock(&kvm->slots_lock);
2618 if (kvm->arch.apic_access_memslot_enabled) {
2619 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
2621 * Clear "enabled" after the memslot is deleted so that a
2622 * different vCPU doesn't get a false negative when checking
2623 * the flag out of slots_lock. No additional memory barrier is
2624 * needed as modifying memslots requires waiting other vCPUs to
2625 * drop SRCU (see above), and false positives are ok as the
2626 * flag is rechecked after acquiring slots_lock.
2628 kvm->arch.apic_access_memslot_enabled = false;
2631 * Mark the memslot as inhibited to prevent reallocating the
2632 * memslot during vCPU creation, e.g. if a vCPU is hotplugged.
2634 kvm->arch.apic_access_memslot_inhibited = true;
2637 mutex_unlock(&kvm->slots_lock);
2639 kvm_vcpu_srcu_read_lock(vcpu);
2642 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2644 struct kvm_lapic *apic = vcpu->arch.apic;
2649 msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
2650 if (kvm_vcpu_is_reset_bsp(vcpu))
2651 msr_val |= MSR_IA32_APICBASE_BSP;
2652 kvm_lapic_set_base(vcpu, msr_val);
2658 /* Stop the timer in case it's a reset to an active apic */
2659 hrtimer_cancel(&apic->lapic_timer.timer);
2661 /* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2663 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2664 kvm_apic_set_version(apic->vcpu);
2666 for (i = 0; i < apic->nr_lvt_entries; i++)
2667 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2668 apic_update_lvtt(apic);
2669 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2670 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2671 kvm_lapic_set_reg(apic, APIC_LVT0,
2672 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2673 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2675 kvm_apic_set_dfr(apic, 0xffffffffU);
2676 apic_set_spiv(apic, 0xff);
2677 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2678 if (!apic_x2apic_mode(apic))
2679 kvm_apic_set_ldr(apic, 0);
2680 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2681 if (!apic_x2apic_mode(apic)) {
2682 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2683 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2685 kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2687 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2688 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2689 for (i = 0; i < 8; i++) {
2690 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2691 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2692 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2694 kvm_apic_update_apicv(vcpu);
2695 update_divide_count(apic);
2696 atomic_set(&apic->lapic_timer.pending, 0);
2698 vcpu->arch.pv_eoi.msr_val = 0;
2699 apic_update_ppr(apic);
2700 if (apic->apicv_active) {
2701 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2702 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2703 static_call_cond(kvm_x86_hwapic_isr_update)(-1);
2706 vcpu->arch.apic_arb_prio = 0;
2707 vcpu->arch.apic_attention = 0;
2709 kvm_recalculate_apic_map(vcpu->kvm);
2713 *----------------------------------------------------------------------
2715 *----------------------------------------------------------------------
2718 static bool lapic_is_periodic(struct kvm_lapic *apic)
2720 return apic_lvtt_period(apic);
2723 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2725 struct kvm_lapic *apic = vcpu->arch.apic;
2727 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2728 return atomic_read(&apic->lapic_timer.pending);
2733 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2735 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2736 int vector, mode, trig_mode;
2738 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2739 vector = reg & APIC_VECTOR_MASK;
2740 mode = reg & APIC_MODE_MASK;
2741 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2742 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2748 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2750 struct kvm_lapic *apic = vcpu->arch.apic;
2753 kvm_apic_local_deliver(apic, APIC_LVT0);
2756 static const struct kvm_io_device_ops apic_mmio_ops = {
2757 .read = apic_mmio_read,
2758 .write = apic_mmio_write,
2761 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2763 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2764 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2766 apic_timer_expired(apic, true);
2768 if (lapic_is_periodic(apic)) {
2769 advance_periodic_target_expiration(apic);
2770 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2771 return HRTIMER_RESTART;
2773 return HRTIMER_NORESTART;
2776 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2778 struct kvm_lapic *apic;
2780 ASSERT(vcpu != NULL);
2782 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2786 vcpu->arch.apic = apic;
2788 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2790 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2792 goto nomem_free_apic;
2796 apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
2798 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2799 HRTIMER_MODE_ABS_HARD);
2800 apic->lapic_timer.timer.function = apic_timer_fn;
2801 if (timer_advance_ns == -1) {
2802 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2803 lapic_timer_advance_dynamic = true;
2805 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2806 lapic_timer_advance_dynamic = false;
2810 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2811 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2813 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2814 static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2815 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2820 vcpu->arch.apic = NULL;
2825 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2827 struct kvm_lapic *apic = vcpu->arch.apic;
2830 if (!kvm_apic_present(vcpu))
2833 __apic_update_ppr(apic, &ppr);
2834 return apic_has_interrupt_for_ppr(apic, ppr);
2836 EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2838 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2840 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2842 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2844 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2845 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2850 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2852 struct kvm_lapic *apic = vcpu->arch.apic;
2854 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2855 kvm_apic_inject_pending_timer_irqs(apic);
2856 atomic_set(&apic->lapic_timer.pending, 0);
2860 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2862 int vector = kvm_apic_has_interrupt(vcpu);
2863 struct kvm_lapic *apic = vcpu->arch.apic;
2870 * We get here even with APIC virtualization enabled, if doing
2871 * nested virtualization and L1 runs with the "acknowledge interrupt
2872 * on exit" mode. Then we cannot inject the interrupt via RVI,
2873 * because the process would deliver it through the IDT.
2876 apic_clear_irr(vector, apic);
2877 if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
2879 * For auto-EOI interrupts, there might be another pending
2880 * interrupt above PPR, so check whether to raise another
2883 apic_update_ppr(apic);
2886 * For normal interrupts, PPR has been raised and there cannot
2887 * be a higher-priority pending interrupt---except if there was
2888 * a concurrent interrupt injection, but that would have
2889 * triggered KVM_REQ_EVENT already.
2891 apic_set_isr(vector, apic);
2892 __apic_update_ppr(apic, &ppr);
2898 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2899 struct kvm_lapic_state *s, bool set)
2901 if (apic_x2apic_mode(vcpu->arch.apic)) {
2902 u32 *id = (u32 *)(s->regs + APIC_ID);
2903 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2906 if (vcpu->kvm->arch.x2apic_format) {
2907 if (*id != vcpu->vcpu_id)
2917 * In x2APIC mode, the LDR is fixed and based on the id. And
2918 * ICR is internally a single 64-bit register, but needs to be
2919 * split to ICR+ICR2 in userspace for backwards compatibility.
2922 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2924 icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
2925 (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
2926 __kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
2928 icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
2929 __kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
2936 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2938 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2941 * Get calculated timer current count for remaining timer period (if
2942 * any) and store it in the returned register set.
2944 __kvm_lapic_set_reg(s->regs, APIC_TMCCT,
2945 __apic_read(vcpu->arch.apic, APIC_TMCCT));
2947 return kvm_apic_state_fixup(vcpu, s, false);
2950 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2952 struct kvm_lapic *apic = vcpu->arch.apic;
2955 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2956 /* set SPIV separately to get count of SW disabled APICs right */
2957 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2959 r = kvm_apic_state_fixup(vcpu, s, true);
2961 kvm_recalculate_apic_map(vcpu->kvm);
2964 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2966 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2967 kvm_recalculate_apic_map(vcpu->kvm);
2968 kvm_apic_set_version(vcpu);
2970 apic_update_ppr(apic);
2971 cancel_apic_timer(apic);
2972 apic->lapic_timer.expired_tscdeadline = 0;
2973 apic_update_lvtt(apic);
2974 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2975 update_divide_count(apic);
2976 __start_apic_timer(apic, APIC_TMCCT);
2977 kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
2978 kvm_apic_update_apicv(vcpu);
2979 if (apic->apicv_active) {
2980 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2981 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
2982 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
2984 kvm_make_request(KVM_REQ_EVENT, vcpu);
2985 if (ioapic_in_kernel(vcpu->kvm))
2986 kvm_rtc_eoi_tracking_restore_one(vcpu);
2988 vcpu->arch.apic_arb_prio = 0;
2993 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2995 struct hrtimer *timer;
2997 if (!lapic_in_kernel(vcpu) ||
2998 kvm_can_post_timer_interrupt(vcpu))
3001 timer = &vcpu->arch.apic->lapic_timer.timer;
3002 if (hrtimer_cancel(timer))
3003 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
3007 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
3009 * Detect whether guest triggered PV EOI since the
3010 * last entry. If yes, set EOI on guests's behalf.
3011 * Clear PV EOI in guest memory in any case.
3013 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
3014 struct kvm_lapic *apic)
3018 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
3019 * and KVM_PV_EOI_ENABLED in guest memory as follows:
3021 * KVM_APIC_PV_EOI_PENDING is unset:
3022 * -> host disabled PV EOI.
3023 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
3024 * -> host enabled PV EOI, guest did not execute EOI yet.
3025 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
3026 * -> host enabled PV EOI, guest executed EOI.
3028 BUG_ON(!pv_eoi_enabled(vcpu));
3030 if (pv_eoi_test_and_clr_pending(vcpu))
3032 vector = apic_set_eoi(apic);
3033 trace_kvm_pv_eoi(apic, vector);
3036 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3040 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
3041 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
3043 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3046 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3050 apic_set_tpr(vcpu->arch.apic, data & 0xff);
3054 * apic_sync_pv_eoi_to_guest - called before vmentry
3056 * Detect whether it's safe to enable PV EOI and
3059 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
3060 struct kvm_lapic *apic)
3062 if (!pv_eoi_enabled(vcpu) ||
3063 /* IRR set or many bits in ISR: could be nested. */
3064 apic->irr_pending ||
3065 /* Cache not set: could be safe but we don't bother. */
3066 apic->highest_isr_cache == -1 ||
3067 /* Need EOI to update ioapic. */
3068 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
3070 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
3071 * so we need not do anything here.
3076 pv_eoi_set_pending(apic->vcpu);
3079 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3082 int max_irr, max_isr;
3083 struct kvm_lapic *apic = vcpu->arch.apic;
3085 apic_sync_pv_eoi_to_guest(vcpu, apic);
3087 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3090 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
3091 max_irr = apic_find_highest_irr(apic);
3094 max_isr = apic_find_highest_isr(apic);
3097 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
3099 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3103 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
3106 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
3107 &vcpu->arch.apic->vapic_cache,
3108 vapic_addr, sizeof(u32)))
3110 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3112 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3115 vcpu->arch.apic->vapic_addr = vapic_addr;
3119 int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
3121 data &= ~APIC_ICR_BUSY;
3123 kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
3124 kvm_lapic_set_reg64(apic, APIC_ICR, data);
3125 trace_kvm_apic_write(APIC_ICR, data);
3129 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
3133 if (reg == APIC_ICR) {
3134 *data = kvm_lapic_get_reg64(apic, APIC_ICR);
3138 if (kvm_lapic_reg_read(apic, reg, 4, &low))
3146 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
3149 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
3150 * can be written as such, all other registers remain accessible only
3151 * through 32-bit reads/writes.
3153 if (reg == APIC_ICR)
3154 return kvm_x2apic_icr_write(apic, data);
3156 /* Bits 63:32 are reserved in all other registers. */
3160 return kvm_lapic_reg_write(apic, reg, (u32)data);
3163 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
3165 struct kvm_lapic *apic = vcpu->arch.apic;
3166 u32 reg = (msr - APIC_BASE_MSR) << 4;
3168 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3171 return kvm_lapic_msr_write(apic, reg, data);
3174 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
3176 struct kvm_lapic *apic = vcpu->arch.apic;
3177 u32 reg = (msr - APIC_BASE_MSR) << 4;
3179 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3182 return kvm_lapic_msr_read(apic, reg, data);
3185 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
3187 if (!lapic_in_kernel(vcpu))
3190 return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
3193 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
3195 if (!lapic_in_kernel(vcpu))
3198 return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
3201 int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3203 u64 addr = data & ~KVM_MSR_ENABLED;
3204 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3205 unsigned long new_len;
3208 if (!IS_ALIGNED(addr, 4))
3211 if (data & KVM_MSR_ENABLED) {
3212 if (addr == ghc->gpa && len <= ghc->len)
3217 ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3222 vcpu->arch.pv_eoi.msr_val = data;
3227 int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
3229 struct kvm_lapic *apic = vcpu->arch.apic;
3233 if (!kvm_apic_has_pending_init_or_sipi(vcpu))
3236 if (is_guest_mode(vcpu)) {
3237 r = kvm_check_nested_events(vcpu);
3239 return r == -EBUSY ? 0 : r;
3241 * Continue processing INIT/SIPI even if a nested VM-Exit
3242 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
3243 * are blocked as a result of transitioning to VMX root mode.
3248 * INITs are blocked while CPU is in specific states (SMM, VMX root
3249 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
3250 * wait-for-SIPI (WFS).
3252 if (!kvm_apic_init_sipi_allowed(vcpu)) {
3253 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3254 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
3258 if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3259 kvm_vcpu_reset(vcpu, true);
3260 if (kvm_vcpu_is_bsp(apic->vcpu))
3261 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3263 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
3265 if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3266 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
3267 /* evaluate pending_events before reading the vector */
3269 sipi_vector = apic->sipi_vector;
3270 static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
3271 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3277 void kvm_lapic_exit(void)
3279 static_key_deferred_flush(&apic_hw_disabled);
3280 WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3281 static_key_deferred_flush(&apic_sw_disabled);
3282 WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));