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 * Deliberately truncate the vCPU ID when detecting a mismatched APIC
233 * ID to avoid false positives if the vCPU ID, i.e. x2APIC ID, is a
234 * 32-bit value. Any unwanted aliasing due to truncation results will
237 if (!apic_x2apic_mode(apic) && xapic_id != (u8)vcpu->vcpu_id)
238 *xapic_id_mismatch = true;
241 * Apply KVM's hotplug hack if userspace has enable 32-bit APIC IDs.
242 * Allow sending events to vCPUs by their x2APIC ID even if the target
243 * vCPU is in legacy xAPIC mode, and silently ignore aliased xAPIC IDs
244 * (the x2APIC ID is truncated to 8 bits, causing IDs > 0xff to wrap
247 * Honor the architectural (and KVM's non-optimized) behavior if
248 * userspace has not enabled 32-bit x2APIC IDs. Each APIC is supposed
249 * to process messages independently. If multiple vCPUs have the same
250 * effective APIC ID, e.g. due to the x2APIC wrap or because the guest
251 * manually modified its xAPIC IDs, events targeting that ID are
252 * supposed to be recognized by all vCPUs with said ID.
254 if (vcpu->kvm->arch.x2apic_format) {
255 /* See also kvm_apic_match_physical_addr(). */
256 if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
257 x2apic_id <= new->max_apic_id)
258 new->phys_map[x2apic_id] = apic;
260 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
261 new->phys_map[xapic_id] = apic;
264 * Disable the optimized map if the physical APIC ID is already
265 * mapped, i.e. is aliased to multiple vCPUs. The optimized
266 * map requires a strict 1:1 mapping between IDs and vCPUs.
268 if (apic_x2apic_mode(apic))
269 physical_id = x2apic_id;
271 physical_id = xapic_id;
273 if (new->phys_map[physical_id])
276 new->phys_map[physical_id] = apic;
282 static void kvm_recalculate_logical_map(struct kvm_apic_map *new,
283 struct kvm_vcpu *vcpu)
285 struct kvm_lapic *apic = vcpu->arch.apic;
286 enum kvm_apic_logical_mode logical_mode;
287 struct kvm_lapic **cluster;
291 if (new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
294 if (!kvm_apic_sw_enabled(apic))
297 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
301 if (apic_x2apic_mode(apic)) {
302 logical_mode = KVM_APIC_MODE_X2APIC;
304 ldr = GET_APIC_LOGICAL_ID(ldr);
305 if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
306 logical_mode = KVM_APIC_MODE_XAPIC_FLAT;
308 logical_mode = KVM_APIC_MODE_XAPIC_CLUSTER;
312 * To optimize logical mode delivery, all software-enabled APICs must
313 * be configured for the same mode.
315 if (new->logical_mode == KVM_APIC_MODE_SW_DISABLED) {
316 new->logical_mode = logical_mode;
317 } else if (new->logical_mode != logical_mode) {
318 new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
323 * In x2APIC mode, the LDR is read-only and derived directly from the
324 * x2APIC ID, thus is guaranteed to be addressable. KVM reuses
325 * kvm_apic_map.phys_map to optimize logical mode x2APIC interrupts by
326 * reversing the LDR calculation to get cluster of APICs, i.e. no
327 * additional work is required.
329 if (apic_x2apic_mode(apic)) {
330 WARN_ON_ONCE(ldr != kvm_apic_calc_x2apic_ldr(kvm_x2apic_id(apic)));
334 if (WARN_ON_ONCE(!kvm_apic_map_get_logical_dest(new, ldr,
336 new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
344 if (!is_power_of_2(mask) || cluster[ldr])
345 new->logical_mode = KVM_APIC_MODE_MAP_DISABLED;
351 * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
353 * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
354 * apic_map_lock_held.
362 void kvm_recalculate_apic_map(struct kvm *kvm)
364 struct kvm_apic_map *new, *old = NULL;
365 struct kvm_vcpu *vcpu;
367 u32 max_id = 255; /* enough space for any xAPIC ID */
368 bool xapic_id_mismatch = false;
370 /* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map. */
371 if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
374 WARN_ONCE(!irqchip_in_kernel(kvm),
375 "Dirty APIC map without an in-kernel local APIC");
377 mutex_lock(&kvm->arch.apic_map_lock);
379 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map
380 * (if clean) or the APIC registers (if dirty).
382 if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
383 DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
384 /* Someone else has updated the map. */
385 mutex_unlock(&kvm->arch.apic_map_lock);
389 kvm_for_each_vcpu(i, vcpu, kvm)
390 if (kvm_apic_present(vcpu))
391 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
393 new = kvzalloc(sizeof(struct kvm_apic_map) +
394 sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
400 new->max_apic_id = max_id;
401 new->logical_mode = KVM_APIC_MODE_SW_DISABLED;
403 kvm_for_each_vcpu(i, vcpu, kvm) {
404 if (!kvm_apic_present(vcpu))
407 if (kvm_recalculate_phys_map(new, vcpu, &xapic_id_mismatch)) {
413 kvm_recalculate_logical_map(new, vcpu);
417 * The optimized map is effectively KVM's internal version of APICv,
418 * and all unwanted aliasing that results in disabling the optimized
419 * map also applies to APICv.
422 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
424 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_ALIASED);
426 if (!new || new->logical_mode == KVM_APIC_MODE_MAP_DISABLED)
427 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
429 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_LOGICAL_ID_ALIASED);
431 if (xapic_id_mismatch)
432 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
434 kvm_clear_apicv_inhibit(kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
436 old = rcu_dereference_protected(kvm->arch.apic_map,
437 lockdep_is_held(&kvm->arch.apic_map_lock));
438 rcu_assign_pointer(kvm->arch.apic_map, new);
440 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
441 * If another update has come in, leave it DIRTY.
443 atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
444 UPDATE_IN_PROGRESS, CLEAN);
445 mutex_unlock(&kvm->arch.apic_map_lock);
448 call_rcu(&old->rcu, kvm_apic_map_free);
450 kvm_make_scan_ioapic_request(kvm);
453 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
455 bool enabled = val & APIC_SPIV_APIC_ENABLED;
457 kvm_lapic_set_reg(apic, APIC_SPIV, val);
459 if (enabled != apic->sw_enabled) {
460 apic->sw_enabled = enabled;
462 static_branch_slow_dec_deferred(&apic_sw_disabled);
464 static_branch_inc(&apic_sw_disabled.key);
466 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
469 /* Check if there are APF page ready requests pending */
471 kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
474 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
476 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
477 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
480 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
482 kvm_lapic_set_reg(apic, APIC_LDR, id);
483 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
486 static inline void kvm_apic_set_dfr(struct kvm_lapic *apic, u32 val)
488 kvm_lapic_set_reg(apic, APIC_DFR, val);
489 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
492 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
494 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
496 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
498 kvm_lapic_set_reg(apic, APIC_ID, id);
499 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
500 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
503 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
505 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
508 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
510 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
513 static inline int apic_lvtt_period(struct kvm_lapic *apic)
515 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
518 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
520 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
523 static inline int apic_lvt_nmi_mode(u32 lvt_val)
525 return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
528 static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
530 return apic->nr_lvt_entries > lvt_index;
533 static inline int kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu *vcpu)
535 return KVM_APIC_MAX_NR_LVT_ENTRIES - !(vcpu->arch.mcg_cap & MCG_CMCI_P);
538 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
540 struct kvm_lapic *apic = vcpu->arch.apic;
543 if (!lapic_in_kernel(vcpu))
546 v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
549 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
550 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
551 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
552 * version first and level-triggered interrupts never get EOIed in
555 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) &&
556 !ioapic_in_kernel(vcpu->kvm))
557 v |= APIC_LVR_DIRECTED_EOI;
558 kvm_lapic_set_reg(apic, APIC_LVR, v);
561 void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu)
563 int nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
564 struct kvm_lapic *apic = vcpu->arch.apic;
567 if (!lapic_in_kernel(vcpu) || nr_lvt_entries == apic->nr_lvt_entries)
570 /* Initialize/mask any "new" LVT entries. */
571 for (i = apic->nr_lvt_entries; i < nr_lvt_entries; i++)
572 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
574 apic->nr_lvt_entries = nr_lvt_entries;
576 /* The number of LVT entries is reflected in the version register. */
577 kvm_apic_set_version(vcpu);
580 static const unsigned int apic_lvt_mask[KVM_APIC_MAX_NR_LVT_ENTRIES] = {
581 [LVT_TIMER] = LVT_MASK, /* timer mode mask added at runtime */
582 [LVT_THERMAL_MONITOR] = LVT_MASK | APIC_MODE_MASK,
583 [LVT_PERFORMANCE_COUNTER] = LVT_MASK | APIC_MODE_MASK,
584 [LVT_LINT0] = LINT_MASK,
585 [LVT_LINT1] = LINT_MASK,
586 [LVT_ERROR] = LVT_MASK,
587 [LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
590 static int find_highest_vector(void *bitmap)
595 for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
596 vec >= 0; vec -= APIC_VECTORS_PER_REG) {
597 reg = bitmap + REG_POS(vec);
599 return __fls(*reg) + vec;
605 static u8 count_vectors(void *bitmap)
611 for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
612 reg = bitmap + REG_POS(vec);
613 count += hweight32(*reg);
619 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
622 u32 pir_val, irr_val, prev_irr_val;
625 max_updated_irr = -1;
628 for (i = vec = 0; i <= 7; i++, vec += 32) {
629 pir_val = READ_ONCE(pir[i]);
630 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
632 prev_irr_val = irr_val;
633 irr_val |= xchg(&pir[i], 0);
634 *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
635 if (prev_irr_val != irr_val) {
637 __fls(irr_val ^ prev_irr_val) + vec;
641 *max_irr = __fls(irr_val) + vec;
644 return ((max_updated_irr != -1) &&
645 (max_updated_irr == *max_irr));
647 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
649 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
651 struct kvm_lapic *apic = vcpu->arch.apic;
653 return __kvm_apic_update_irr(pir, apic->regs, max_irr);
655 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
657 static inline int apic_search_irr(struct kvm_lapic *apic)
659 return find_highest_vector(apic->regs + APIC_IRR);
662 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
667 * Note that irr_pending is just a hint. It will be always
668 * true with virtual interrupt delivery enabled.
670 if (!apic->irr_pending)
673 result = apic_search_irr(apic);
674 ASSERT(result == -1 || result >= 16);
679 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
681 if (unlikely(apic->apicv_active)) {
682 /* need to update RVI */
683 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
684 static_call_cond(kvm_x86_hwapic_irr_update)(apic->vcpu,
685 apic_find_highest_irr(apic));
687 apic->irr_pending = false;
688 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
689 if (apic_search_irr(apic) != -1)
690 apic->irr_pending = true;
694 void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
696 apic_clear_irr(vec, vcpu->arch.apic);
698 EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
700 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
702 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
706 * With APIC virtualization enabled, all caching is disabled
707 * because the processor can modify ISR under the hood. Instead
710 if (unlikely(apic->apicv_active))
711 static_call_cond(kvm_x86_hwapic_isr_update)(vec);
714 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
716 * ISR (in service register) bit is set when injecting an interrupt.
717 * The highest vector is injected. Thus the latest bit set matches
718 * the highest bit in ISR.
720 apic->highest_isr_cache = vec;
724 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
729 * Note that isr_count is always 1, and highest_isr_cache
730 * is always -1, with APIC virtualization enabled.
732 if (!apic->isr_count)
734 if (likely(apic->highest_isr_cache != -1))
735 return apic->highest_isr_cache;
737 result = find_highest_vector(apic->regs + APIC_ISR);
738 ASSERT(result == -1 || result >= 16);
743 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
745 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
749 * We do get here for APIC virtualization enabled if the guest
750 * uses the Hyper-V APIC enlightenment. In this case we may need
751 * to trigger a new interrupt delivery by writing the SVI field;
752 * on the other hand isr_count and highest_isr_cache are unused
753 * and must be left alone.
755 if (unlikely(apic->apicv_active))
756 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
759 BUG_ON(apic->isr_count < 0);
760 apic->highest_isr_cache = -1;
764 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
766 /* This may race with setting of irr in __apic_accept_irq() and
767 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
768 * will cause vmexit immediately and the value will be recalculated
769 * on the next vmentry.
771 return apic_find_highest_irr(vcpu->arch.apic);
773 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
775 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
776 int vector, int level, int trig_mode,
777 struct dest_map *dest_map);
779 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
780 struct dest_map *dest_map)
782 struct kvm_lapic *apic = vcpu->arch.apic;
784 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
785 irq->level, irq->trig_mode, dest_map);
788 static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
789 struct kvm_lapic_irq *irq, u32 min)
792 struct kvm_vcpu *vcpu;
794 if (min > map->max_apic_id)
797 for_each_set_bit(i, ipi_bitmap,
798 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
799 if (map->phys_map[min + i]) {
800 vcpu = map->phys_map[min + i]->vcpu;
801 count += kvm_apic_set_irq(vcpu, irq, NULL);
808 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
809 unsigned long ipi_bitmap_high, u32 min,
810 unsigned long icr, int op_64_bit)
812 struct kvm_apic_map *map;
813 struct kvm_lapic_irq irq = {0};
814 int cluster_size = op_64_bit ? 64 : 32;
817 if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
820 irq.vector = icr & APIC_VECTOR_MASK;
821 irq.delivery_mode = icr & APIC_MODE_MASK;
822 irq.level = (icr & APIC_INT_ASSERT) != 0;
823 irq.trig_mode = icr & APIC_INT_LEVELTRIG;
826 map = rcu_dereference(kvm->arch.apic_map);
830 count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
832 count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
839 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
842 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
846 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
849 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
853 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
855 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
858 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
860 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
863 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
866 static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
870 if (pv_eoi_get_user(vcpu, &val) < 0)
873 val &= KVM_PV_EOI_ENABLED;
875 if (val && pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0)
879 * Clear pending bit in any case: it will be set again on vmentry.
880 * While this might not be ideal from performance point of view,
881 * this makes sure pv eoi is only enabled when we know it's safe.
883 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
888 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
891 if (kvm_x86_ops.sync_pir_to_irr)
892 highest_irr = static_call(kvm_x86_sync_pir_to_irr)(apic->vcpu);
894 highest_irr = apic_find_highest_irr(apic);
895 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
900 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
902 u32 tpr, isrv, ppr, old_ppr;
905 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
906 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
907 isr = apic_find_highest_isr(apic);
908 isrv = (isr != -1) ? isr : 0;
910 if ((tpr & 0xf0) >= (isrv & 0xf0))
917 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
919 return ppr < old_ppr;
922 static void apic_update_ppr(struct kvm_lapic *apic)
926 if (__apic_update_ppr(apic, &ppr) &&
927 apic_has_interrupt_for_ppr(apic, ppr) != -1)
928 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
931 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
933 apic_update_ppr(vcpu->arch.apic);
935 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
937 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
939 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
940 apic_update_ppr(apic);
943 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
945 return mda == (apic_x2apic_mode(apic) ?
946 X2APIC_BROADCAST : APIC_BROADCAST);
949 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
951 if (kvm_apic_broadcast(apic, mda))
955 * Hotplug hack: Accept interrupts for vCPUs in xAPIC mode as if they
956 * were in x2APIC mode if the target APIC ID can't be encoded as an
957 * xAPIC ID. This allows unique addressing of hotplugged vCPUs (which
958 * start in xAPIC mode) with an APIC ID that is unaddressable in xAPIC
959 * mode. Match the x2APIC ID if and only if the target APIC ID can't
960 * be encoded in xAPIC to avoid spurious matches against a vCPU that
961 * changed its (addressable) xAPIC ID (which is writable).
963 if (apic_x2apic_mode(apic) || mda > 0xff)
964 return mda == kvm_x2apic_id(apic);
966 return mda == kvm_xapic_id(apic);
969 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
973 if (kvm_apic_broadcast(apic, mda))
976 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
978 if (apic_x2apic_mode(apic))
979 return ((logical_id >> 16) == (mda >> 16))
980 && (logical_id & mda & 0xffff) != 0;
982 logical_id = GET_APIC_LOGICAL_ID(logical_id);
984 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
986 return (logical_id & mda) != 0;
987 case APIC_DFR_CLUSTER:
988 return ((logical_id >> 4) == (mda >> 4))
989 && (logical_id & mda & 0xf) != 0;
995 /* The KVM local APIC implementation has two quirks:
997 * - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
998 * in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
999 * KVM doesn't do that aliasing.
1001 * - in-kernel IOAPIC messages have to be delivered directly to
1002 * x2APIC, because the kernel does not support interrupt remapping.
1003 * In order to support broadcast without interrupt remapping, x2APIC
1004 * rewrites the destination of non-IPI messages from APIC_BROADCAST
1005 * to X2APIC_BROADCAST.
1007 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API. This is
1008 * important when userspace wants to use x2APIC-format MSIs, because
1009 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
1011 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
1012 struct kvm_lapic *source, struct kvm_lapic *target)
1014 bool ipi = source != NULL;
1016 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
1017 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
1018 return X2APIC_BROADCAST;
1023 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
1024 int shorthand, unsigned int dest, int dest_mode)
1026 struct kvm_lapic *target = vcpu->arch.apic;
1027 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
1030 switch (shorthand) {
1031 case APIC_DEST_NOSHORT:
1032 if (dest_mode == APIC_DEST_PHYSICAL)
1033 return kvm_apic_match_physical_addr(target, mda);
1035 return kvm_apic_match_logical_addr(target, mda);
1036 case APIC_DEST_SELF:
1037 return target == source;
1038 case APIC_DEST_ALLINC:
1040 case APIC_DEST_ALLBUT:
1041 return target != source;
1046 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
1048 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
1049 const unsigned long *bitmap, u32 bitmap_size)
1054 mod = vector % dest_vcpus;
1056 for (i = 0; i <= mod; i++) {
1057 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
1058 BUG_ON(idx == bitmap_size);
1064 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
1066 if (!kvm->arch.disabled_lapic_found) {
1067 kvm->arch.disabled_lapic_found = true;
1068 pr_info("Disabled LAPIC found during irq injection\n");
1072 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
1073 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
1075 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
1076 if ((irq->dest_id == APIC_BROADCAST &&
1077 map->logical_mode != KVM_APIC_MODE_X2APIC))
1079 if (irq->dest_id == X2APIC_BROADCAST)
1082 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
1083 if (irq->dest_id == (x2apic_ipi ?
1084 X2APIC_BROADCAST : APIC_BROADCAST))
1091 /* Return true if the interrupt can be handled by using *bitmap as index mask
1092 * for valid destinations in *dst array.
1093 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
1094 * Note: we may have zero kvm_lapic destinations when we return true, which
1095 * means that the interrupt should be dropped. In this case, *bitmap would be
1096 * zero and *dst undefined.
1098 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
1099 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
1100 struct kvm_apic_map *map, struct kvm_lapic ***dst,
1101 unsigned long *bitmap)
1105 if (irq->shorthand == APIC_DEST_SELF && src) {
1109 } else if (irq->shorthand)
1112 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
1115 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
1116 if (irq->dest_id > map->max_apic_id) {
1119 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
1120 *dst = &map->phys_map[dest_id];
1127 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1131 if (!kvm_lowest_prio_delivery(irq))
1134 if (!kvm_vector_hashing_enabled()) {
1136 for_each_set_bit(i, bitmap, 16) {
1141 else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
1142 (*dst)[lowest]->vcpu) < 0)
1149 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
1152 if (!(*dst)[lowest]) {
1153 kvm_apic_disabled_lapic_found(kvm);
1159 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
1164 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
1165 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
1167 struct kvm_apic_map *map;
1168 unsigned long bitmap;
1169 struct kvm_lapic **dst = NULL;
1175 if (irq->shorthand == APIC_DEST_SELF) {
1176 if (KVM_BUG_ON(!src, kvm)) {
1180 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
1185 map = rcu_dereference(kvm->arch.apic_map);
1187 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
1190 for_each_set_bit(i, &bitmap, 16) {
1193 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
1202 * This routine tries to handle interrupts in posted mode, here is how
1203 * it deals with different cases:
1204 * - For single-destination interrupts, handle it in posted mode
1205 * - Else if vector hashing is enabled and it is a lowest-priority
1206 * interrupt, handle it in posted mode and use the following mechanism
1207 * to find the destination vCPU.
1208 * 1. For lowest-priority interrupts, store all the possible
1209 * destination vCPUs in an array.
1210 * 2. Use "guest vector % max number of destination vCPUs" to find
1211 * the right destination vCPU in the array for the lowest-priority
1213 * - Otherwise, use remapped mode to inject the interrupt.
1215 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
1216 struct kvm_vcpu **dest_vcpu)
1218 struct kvm_apic_map *map;
1219 unsigned long bitmap;
1220 struct kvm_lapic **dst = NULL;
1227 map = rcu_dereference(kvm->arch.apic_map);
1229 if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1230 hweight16(bitmap) == 1) {
1231 unsigned long i = find_first_bit(&bitmap, 16);
1234 *dest_vcpu = dst[i]->vcpu;
1244 * Add a pending IRQ into lapic.
1245 * Return 1 if successfully added and 0 if discarded.
1247 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1248 int vector, int level, int trig_mode,
1249 struct dest_map *dest_map)
1252 struct kvm_vcpu *vcpu = apic->vcpu;
1254 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1256 switch (delivery_mode) {
1257 case APIC_DM_LOWEST:
1258 vcpu->arch.apic_arb_prio++;
1261 if (unlikely(trig_mode && !level))
1264 /* FIXME add logic for vcpu on reset */
1265 if (unlikely(!apic_enabled(apic)))
1271 __set_bit(vcpu->vcpu_id, dest_map->map);
1272 dest_map->vectors[vcpu->vcpu_id] = vector;
1275 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1277 kvm_lapic_set_vector(vector,
1278 apic->regs + APIC_TMR);
1280 kvm_lapic_clear_vector(vector,
1281 apic->regs + APIC_TMR);
1284 static_call(kvm_x86_deliver_interrupt)(apic, delivery_mode,
1290 vcpu->arch.pv.pv_unhalted = 1;
1291 kvm_make_request(KVM_REQ_EVENT, vcpu);
1292 kvm_vcpu_kick(vcpu);
1296 if (!kvm_inject_smi(vcpu)) {
1297 kvm_vcpu_kick(vcpu);
1304 kvm_inject_nmi(vcpu);
1305 kvm_vcpu_kick(vcpu);
1309 if (!trig_mode || level) {
1311 /* assumes that there are only KVM_APIC_INIT/SIPI */
1312 apic->pending_events = (1UL << KVM_APIC_INIT);
1313 kvm_make_request(KVM_REQ_EVENT, vcpu);
1314 kvm_vcpu_kick(vcpu);
1318 case APIC_DM_STARTUP:
1320 apic->sipi_vector = vector;
1321 /* make sure sipi_vector is visible for the receiver */
1323 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1324 kvm_make_request(KVM_REQ_EVENT, vcpu);
1325 kvm_vcpu_kick(vcpu);
1328 case APIC_DM_EXTINT:
1330 * Should only be called by kvm_apic_local_deliver() with LVT0,
1331 * before NMI watchdog was enabled. Already handled by
1332 * kvm_apic_accept_pic_intr().
1337 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1345 * This routine identifies the destination vcpus mask meant to receive the
1346 * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
1347 * out the destination vcpus array and set the bitmap or it traverses to
1348 * each available vcpu to identify the same.
1350 void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
1351 unsigned long *vcpu_bitmap)
1353 struct kvm_lapic **dest_vcpu = NULL;
1354 struct kvm_lapic *src = NULL;
1355 struct kvm_apic_map *map;
1356 struct kvm_vcpu *vcpu;
1357 unsigned long bitmap, i;
1362 map = rcu_dereference(kvm->arch.apic_map);
1364 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
1367 for_each_set_bit(i, &bitmap, 16) {
1370 vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
1371 __set_bit(vcpu_idx, vcpu_bitmap);
1374 kvm_for_each_vcpu(i, vcpu, kvm) {
1375 if (!kvm_apic_present(vcpu))
1377 if (!kvm_apic_match_dest(vcpu, NULL,
1382 __set_bit(i, vcpu_bitmap);
1388 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1390 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1393 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1395 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1398 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1402 /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1403 if (!kvm_ioapic_handles_vector(apic, vector))
1406 /* Request a KVM exit to inform the userspace IOAPIC. */
1407 if (irqchip_split(apic->vcpu->kvm)) {
1408 apic->vcpu->arch.pending_ioapic_eoi = vector;
1409 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1413 if (apic_test_vector(vector, apic->regs + APIC_TMR))
1414 trigger_mode = IOAPIC_LEVEL_TRIG;
1416 trigger_mode = IOAPIC_EDGE_TRIG;
1418 kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1421 static int apic_set_eoi(struct kvm_lapic *apic)
1423 int vector = apic_find_highest_isr(apic);
1425 trace_kvm_eoi(apic, vector);
1428 * Not every write EOI will has corresponding ISR,
1429 * one example is when Kernel check timer on setup_IO_APIC
1434 apic_clear_isr(vector, apic);
1435 apic_update_ppr(apic);
1437 if (to_hv_vcpu(apic->vcpu) &&
1438 test_bit(vector, to_hv_synic(apic->vcpu)->vec_bitmap))
1439 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1441 kvm_ioapic_send_eoi(apic, vector);
1442 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1447 * this interface assumes a trap-like exit, which has already finished
1448 * desired side effect including vISR and vPPR update.
1450 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1452 struct kvm_lapic *apic = vcpu->arch.apic;
1454 trace_kvm_eoi(apic, vector);
1456 kvm_ioapic_send_eoi(apic, vector);
1457 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1459 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1461 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1463 struct kvm_lapic_irq irq;
1465 /* KVM has no delay and should always clear the BUSY/PENDING flag. */
1466 WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1468 irq.vector = icr_low & APIC_VECTOR_MASK;
1469 irq.delivery_mode = icr_low & APIC_MODE_MASK;
1470 irq.dest_mode = icr_low & APIC_DEST_MASK;
1471 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1472 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1473 irq.shorthand = icr_low & APIC_SHORT_MASK;
1474 irq.msi_redir_hint = false;
1475 if (apic_x2apic_mode(apic))
1476 irq.dest_id = icr_high;
1478 irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
1480 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1482 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1484 EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1486 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1488 ktime_t remaining, now;
1491 ASSERT(apic != NULL);
1493 /* if initial count is 0, current count should also be 0 */
1494 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1495 apic->lapic_timer.period == 0)
1499 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1500 if (ktime_to_ns(remaining) < 0)
1503 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1504 return div64_u64(ns, (APIC_BUS_CYCLE_NS * apic->divide_count));
1507 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1509 struct kvm_vcpu *vcpu = apic->vcpu;
1510 struct kvm_run *run = vcpu->run;
1512 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1513 run->tpr_access.rip = kvm_rip_read(vcpu);
1514 run->tpr_access.is_write = write;
1517 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1519 if (apic->vcpu->arch.tpr_access_reporting)
1520 __report_tpr_access(apic, write);
1523 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1527 if (offset >= LAPIC_MMIO_LENGTH)
1534 case APIC_TMCCT: /* Timer CCR */
1535 if (apic_lvtt_tscdeadline(apic))
1538 val = apic_get_tmcct(apic);
1541 apic_update_ppr(apic);
1542 val = kvm_lapic_get_reg(apic, offset);
1545 report_tpr_access(apic, false);
1548 val = kvm_lapic_get_reg(apic, offset);
1555 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1557 return container_of(dev, struct kvm_lapic, dev);
1560 #define APIC_REG_MASK(reg) (1ull << ((reg) >> 4))
1561 #define APIC_REGS_MASK(first, count) \
1562 (APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1564 static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1567 unsigned char alignment = offset & 0xf;
1569 /* this bitmask has a bit cleared for each reserved register */
1570 u64 valid_reg_mask =
1571 APIC_REG_MASK(APIC_ID) |
1572 APIC_REG_MASK(APIC_LVR) |
1573 APIC_REG_MASK(APIC_TASKPRI) |
1574 APIC_REG_MASK(APIC_PROCPRI) |
1575 APIC_REG_MASK(APIC_LDR) |
1576 APIC_REG_MASK(APIC_DFR) |
1577 APIC_REG_MASK(APIC_SPIV) |
1578 APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1579 APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1580 APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1581 APIC_REG_MASK(APIC_ESR) |
1582 APIC_REG_MASK(APIC_ICR) |
1583 APIC_REG_MASK(APIC_LVTT) |
1584 APIC_REG_MASK(APIC_LVTTHMR) |
1585 APIC_REG_MASK(APIC_LVTPC) |
1586 APIC_REG_MASK(APIC_LVT0) |
1587 APIC_REG_MASK(APIC_LVT1) |
1588 APIC_REG_MASK(APIC_LVTERR) |
1589 APIC_REG_MASK(APIC_TMICT) |
1590 APIC_REG_MASK(APIC_TMCCT) |
1591 APIC_REG_MASK(APIC_TDCR);
1593 if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
1594 valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
1597 * ARBPRI and ICR2 are not valid in x2APIC mode. WARN if KVM reads ICR
1598 * in x2APIC mode as it's an 8-byte register in x2APIC and needs to be
1599 * manually handled by the caller.
1601 if (!apic_x2apic_mode(apic))
1602 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1603 APIC_REG_MASK(APIC_ICR2);
1605 WARN_ON_ONCE(offset == APIC_ICR);
1607 if (alignment + len > 4)
1610 if (offset > 0x3f0 || !(valid_reg_mask & APIC_REG_MASK(offset)))
1613 result = __apic_read(apic, offset & ~0xf);
1615 trace_kvm_apic_read(offset, result);
1621 memcpy(data, (char *)&result + alignment, len);
1624 printk(KERN_ERR "Local APIC read with len = %x, "
1625 "should be 1,2, or 4 instead\n", len);
1631 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1633 return addr >= apic->base_address &&
1634 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1637 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1638 gpa_t address, int len, void *data)
1640 struct kvm_lapic *apic = to_lapic(this);
1641 u32 offset = address - apic->base_address;
1643 if (!apic_mmio_in_range(apic, address))
1646 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1647 if (!kvm_check_has_quirk(vcpu->kvm,
1648 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1651 memset(data, 0xff, len);
1655 kvm_lapic_reg_read(apic, offset, len, data);
1660 static void update_divide_count(struct kvm_lapic *apic)
1662 u32 tmp1, tmp2, tdcr;
1664 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1666 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1667 apic->divide_count = 0x1 << (tmp2 & 0x7);
1670 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1673 * Do not allow the guest to program periodic timers with small
1674 * interval, since the hrtimers are not throttled by the host
1677 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1678 s64 min_period = min_timer_period_us * 1000LL;
1680 if (apic->lapic_timer.period < min_period) {
1681 pr_info_ratelimited(
1682 "vcpu %i: requested %lld ns "
1683 "lapic timer period limited to %lld ns\n",
1684 apic->vcpu->vcpu_id,
1685 apic->lapic_timer.period, min_period);
1686 apic->lapic_timer.period = min_period;
1691 static void cancel_hv_timer(struct kvm_lapic *apic);
1693 static void cancel_apic_timer(struct kvm_lapic *apic)
1695 hrtimer_cancel(&apic->lapic_timer.timer);
1697 if (apic->lapic_timer.hv_timer_in_use)
1698 cancel_hv_timer(apic);
1700 atomic_set(&apic->lapic_timer.pending, 0);
1703 static void apic_update_lvtt(struct kvm_lapic *apic)
1705 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1706 apic->lapic_timer.timer_mode_mask;
1708 if (apic->lapic_timer.timer_mode != timer_mode) {
1709 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1710 APIC_LVT_TIMER_TSCDEADLINE)) {
1711 cancel_apic_timer(apic);
1712 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1713 apic->lapic_timer.period = 0;
1714 apic->lapic_timer.tscdeadline = 0;
1716 apic->lapic_timer.timer_mode = timer_mode;
1717 limit_periodic_timer_frequency(apic);
1722 * On APICv, this test will cause a busy wait
1723 * during a higher-priority task.
1726 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1728 struct kvm_lapic *apic = vcpu->arch.apic;
1729 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1731 if (kvm_apic_hw_enabled(apic)) {
1732 int vec = reg & APIC_VECTOR_MASK;
1733 void *bitmap = apic->regs + APIC_ISR;
1735 if (apic->apicv_active)
1736 bitmap = apic->regs + APIC_IRR;
1738 if (apic_test_vector(vec, bitmap))
1744 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1746 u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1749 * If the guest TSC is running at a different ratio than the host, then
1750 * convert the delay to nanoseconds to achieve an accurate delay. Note
1751 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1752 * always for VMX enabled hardware.
1754 if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1755 __delay(min(guest_cycles,
1756 nsec_to_cycles(vcpu, timer_advance_ns)));
1758 u64 delay_ns = guest_cycles * 1000000ULL;
1759 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1760 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1764 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1765 s64 advance_expire_delta)
1767 struct kvm_lapic *apic = vcpu->arch.apic;
1768 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1771 /* Do not adjust for tiny fluctuations or large random spikes. */
1772 if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1773 abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1777 if (advance_expire_delta < 0) {
1778 ns = -advance_expire_delta * 1000000ULL;
1779 do_div(ns, vcpu->arch.virtual_tsc_khz);
1780 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1783 ns = advance_expire_delta * 1000000ULL;
1784 do_div(ns, vcpu->arch.virtual_tsc_khz);
1785 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1788 if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1789 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1790 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1793 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1795 struct kvm_lapic *apic = vcpu->arch.apic;
1796 u64 guest_tsc, tsc_deadline;
1798 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1799 apic->lapic_timer.expired_tscdeadline = 0;
1800 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1801 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1803 if (lapic_timer_advance_dynamic) {
1804 adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
1806 * If the timer fired early, reread the TSC to account for the
1807 * overhead of the above adjustment to avoid waiting longer
1808 * than is necessary.
1810 if (guest_tsc < tsc_deadline)
1811 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1814 if (guest_tsc < tsc_deadline)
1815 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1818 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1820 if (lapic_in_kernel(vcpu) &&
1821 vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1822 vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1823 lapic_timer_int_injected(vcpu))
1824 __kvm_wait_lapic_expire(vcpu);
1826 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1828 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1830 struct kvm_timer *ktimer = &apic->lapic_timer;
1832 kvm_apic_local_deliver(apic, APIC_LVTT);
1833 if (apic_lvtt_tscdeadline(apic)) {
1834 ktimer->tscdeadline = 0;
1835 } else if (apic_lvtt_oneshot(apic)) {
1836 ktimer->tscdeadline = 0;
1837 ktimer->target_expiration = 0;
1841 static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
1843 struct kvm_vcpu *vcpu = apic->vcpu;
1844 struct kvm_timer *ktimer = &apic->lapic_timer;
1846 if (atomic_read(&apic->lapic_timer.pending))
1849 if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1850 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1852 if (!from_timer_fn && apic->apicv_active) {
1853 WARN_ON(kvm_get_running_vcpu() != vcpu);
1854 kvm_apic_inject_pending_timer_irqs(apic);
1858 if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1860 * Ensure the guest's timer has truly expired before posting an
1861 * interrupt. Open code the relevant checks to avoid querying
1862 * lapic_timer_int_injected(), which will be false since the
1863 * interrupt isn't yet injected. Waiting until after injecting
1864 * is not an option since that won't help a posted interrupt.
1866 if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1867 vcpu->arch.apic->lapic_timer.timer_advance_ns)
1868 __kvm_wait_lapic_expire(vcpu);
1869 kvm_apic_inject_pending_timer_irqs(apic);
1873 atomic_inc(&apic->lapic_timer.pending);
1874 kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1876 kvm_vcpu_kick(vcpu);
1879 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1881 struct kvm_timer *ktimer = &apic->lapic_timer;
1882 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1885 struct kvm_vcpu *vcpu = apic->vcpu;
1886 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1887 unsigned long flags;
1890 if (unlikely(!tscdeadline || !this_tsc_khz))
1893 local_irq_save(flags);
1896 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1898 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1899 do_div(ns, this_tsc_khz);
1901 if (likely(tscdeadline > guest_tsc) &&
1902 likely(ns > apic->lapic_timer.timer_advance_ns)) {
1903 expire = ktime_add_ns(now, ns);
1904 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1905 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1907 apic_timer_expired(apic, false);
1909 local_irq_restore(flags);
1912 static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1914 return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
1917 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1919 ktime_t now, remaining;
1920 u64 ns_remaining_old, ns_remaining_new;
1922 apic->lapic_timer.period =
1923 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1924 limit_periodic_timer_frequency(apic);
1927 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1928 if (ktime_to_ns(remaining) < 0)
1931 ns_remaining_old = ktime_to_ns(remaining);
1932 ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1933 apic->divide_count, old_divisor);
1935 apic->lapic_timer.tscdeadline +=
1936 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1937 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1938 apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1941 static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1948 apic->lapic_timer.period =
1949 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1951 if (!apic->lapic_timer.period) {
1952 apic->lapic_timer.tscdeadline = 0;
1956 limit_periodic_timer_frequency(apic);
1957 deadline = apic->lapic_timer.period;
1959 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1960 if (unlikely(count_reg != APIC_TMICT)) {
1961 deadline = tmict_to_ns(apic,
1962 kvm_lapic_get_reg(apic, count_reg));
1963 if (unlikely(deadline <= 0))
1964 deadline = apic->lapic_timer.period;
1965 else if (unlikely(deadline > apic->lapic_timer.period)) {
1966 pr_info_ratelimited(
1967 "vcpu %i: requested lapic timer restore with "
1968 "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
1969 "Using initial count to start timer.\n",
1970 apic->vcpu->vcpu_id,
1972 kvm_lapic_get_reg(apic, count_reg),
1973 deadline, apic->lapic_timer.period);
1974 kvm_lapic_set_reg(apic, count_reg, 0);
1975 deadline = apic->lapic_timer.period;
1980 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1981 nsec_to_cycles(apic->vcpu, deadline);
1982 apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
1987 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1989 ktime_t now = ktime_get();
1994 * Synchronize both deadlines to the same time source or
1995 * differences in the periods (caused by differences in the
1996 * underlying clocks or numerical approximation errors) will
1997 * cause the two to drift apart over time as the errors
2000 apic->lapic_timer.target_expiration =
2001 ktime_add_ns(apic->lapic_timer.target_expiration,
2002 apic->lapic_timer.period);
2003 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
2004 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2005 nsec_to_cycles(apic->vcpu, delta);
2008 static void start_sw_period(struct kvm_lapic *apic)
2010 if (!apic->lapic_timer.period)
2013 if (ktime_after(ktime_get(),
2014 apic->lapic_timer.target_expiration)) {
2015 apic_timer_expired(apic, false);
2017 if (apic_lvtt_oneshot(apic))
2020 advance_periodic_target_expiration(apic);
2023 hrtimer_start(&apic->lapic_timer.timer,
2024 apic->lapic_timer.target_expiration,
2025 HRTIMER_MODE_ABS_HARD);
2028 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2030 if (!lapic_in_kernel(vcpu))
2033 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2036 static void cancel_hv_timer(struct kvm_lapic *apic)
2038 WARN_ON(preemptible());
2039 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2040 static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
2041 apic->lapic_timer.hv_timer_in_use = false;
2044 static bool start_hv_timer(struct kvm_lapic *apic)
2046 struct kvm_timer *ktimer = &apic->lapic_timer;
2047 struct kvm_vcpu *vcpu = apic->vcpu;
2050 WARN_ON(preemptible());
2051 if (!kvm_can_use_hv_timer(vcpu))
2054 if (!ktimer->tscdeadline)
2057 if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
2060 ktimer->hv_timer_in_use = true;
2061 hrtimer_cancel(&ktimer->timer);
2064 * To simplify handling the periodic timer, leave the hv timer running
2065 * even if the deadline timer has expired, i.e. rely on the resulting
2066 * VM-Exit to recompute the periodic timer's target expiration.
2068 if (!apic_lvtt_period(apic)) {
2070 * Cancel the hv timer if the sw timer fired while the hv timer
2071 * was being programmed, or if the hv timer itself expired.
2073 if (atomic_read(&ktimer->pending)) {
2074 cancel_hv_timer(apic);
2075 } else if (expired) {
2076 apic_timer_expired(apic, false);
2077 cancel_hv_timer(apic);
2081 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
2086 static void start_sw_timer(struct kvm_lapic *apic)
2088 struct kvm_timer *ktimer = &apic->lapic_timer;
2090 WARN_ON(preemptible());
2091 if (apic->lapic_timer.hv_timer_in_use)
2092 cancel_hv_timer(apic);
2093 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
2096 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2097 start_sw_period(apic);
2098 else if (apic_lvtt_tscdeadline(apic))
2099 start_sw_tscdeadline(apic);
2100 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
2103 static void restart_apic_timer(struct kvm_lapic *apic)
2107 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
2110 if (!start_hv_timer(apic))
2111 start_sw_timer(apic);
2116 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
2118 struct kvm_lapic *apic = vcpu->arch.apic;
2121 /* If the preempt notifier has already run, it also called apic_timer_expired */
2122 if (!apic->lapic_timer.hv_timer_in_use)
2124 WARN_ON(kvm_vcpu_is_blocking(vcpu));
2125 apic_timer_expired(apic, false);
2126 cancel_hv_timer(apic);
2128 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
2129 advance_periodic_target_expiration(apic);
2130 restart_apic_timer(apic);
2135 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
2137 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2139 restart_apic_timer(vcpu->arch.apic);
2142 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2144 struct kvm_lapic *apic = vcpu->arch.apic;
2147 /* Possibly the TSC deadline timer is not enabled yet */
2148 if (apic->lapic_timer.hv_timer_in_use)
2149 start_sw_timer(apic);
2153 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2155 struct kvm_lapic *apic = vcpu->arch.apic;
2157 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2158 restart_apic_timer(apic);
2161 static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2163 atomic_set(&apic->lapic_timer.pending, 0);
2165 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2166 && !set_target_expiration(apic, count_reg))
2169 restart_apic_timer(apic);
2172 static void start_apic_timer(struct kvm_lapic *apic)
2174 __start_apic_timer(apic, APIC_TMICT);
2177 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2179 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2181 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
2182 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
2183 if (lvt0_in_nmi_mode) {
2184 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2186 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2190 static int get_lvt_index(u32 reg)
2192 if (reg == APIC_LVTCMCI)
2194 if (reg < APIC_LVTT || reg > APIC_LVTERR)
2196 return array_index_nospec(
2197 (reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
2200 static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2204 trace_kvm_apic_write(reg, val);
2207 case APIC_ID: /* Local APIC ID */
2208 if (!apic_x2apic_mode(apic)) {
2209 kvm_apic_set_xapic_id(apic, val >> 24);
2216 report_tpr_access(apic, true);
2217 apic_set_tpr(apic, val & 0xff);
2225 if (!apic_x2apic_mode(apic))
2226 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
2232 if (!apic_x2apic_mode(apic))
2233 kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2240 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2241 mask |= APIC_SPIV_DIRECTED_EOI;
2242 apic_set_spiv(apic, val & mask);
2243 if (!(val & APIC_SPIV_APIC_ENABLED)) {
2246 for (i = 0; i < apic->nr_lvt_entries; i++) {
2247 kvm_lapic_set_reg(apic, APIC_LVTx(i),
2248 kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2250 apic_update_lvtt(apic);
2251 atomic_set(&apic->lapic_timer.pending, 0);
2257 WARN_ON_ONCE(apic_x2apic_mode(apic));
2259 /* No delay here, so we always clear the pending bit */
2260 val &= ~APIC_ICR_BUSY;
2261 kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2262 kvm_lapic_set_reg(apic, APIC_ICR, val);
2265 if (apic_x2apic_mode(apic))
2268 kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2272 apic_manage_nmi_watchdog(apic, val);
2278 case APIC_LVTCMCI: {
2279 u32 index = get_lvt_index(reg);
2280 if (!kvm_lapic_lvt_supported(apic, index)) {
2284 if (!kvm_apic_sw_enabled(apic))
2285 val |= APIC_LVT_MASKED;
2286 val &= apic_lvt_mask[index];
2287 kvm_lapic_set_reg(apic, reg, val);
2292 if (!kvm_apic_sw_enabled(apic))
2293 val |= APIC_LVT_MASKED;
2294 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
2295 kvm_lapic_set_reg(apic, APIC_LVTT, val);
2296 apic_update_lvtt(apic);
2300 if (apic_lvtt_tscdeadline(apic))
2303 cancel_apic_timer(apic);
2304 kvm_lapic_set_reg(apic, APIC_TMICT, val);
2305 start_apic_timer(apic);
2309 uint32_t old_divisor = apic->divide_count;
2311 kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2312 update_divide_count(apic);
2313 if (apic->divide_count != old_divisor &&
2314 apic->lapic_timer.period) {
2315 hrtimer_cancel(&apic->lapic_timer.timer);
2316 update_target_expiration(apic, old_divisor);
2317 restart_apic_timer(apic);
2322 if (apic_x2apic_mode(apic) && val != 0)
2328 * Self-IPI exists only when x2APIC is enabled. Bits 7:0 hold
2329 * the vector, everything else is reserved.
2331 if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
2334 kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
2342 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2343 * was toggled, the APIC ID changed, etc... The maps are marked dirty
2344 * on relevant changes, i.e. this is a nop for most writes.
2346 kvm_recalculate_apic_map(apic->vcpu->kvm);
2351 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2352 gpa_t address, int len, const void *data)
2354 struct kvm_lapic *apic = to_lapic(this);
2355 unsigned int offset = address - apic->base_address;
2358 if (!apic_mmio_in_range(apic, address))
2361 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2362 if (!kvm_check_has_quirk(vcpu->kvm,
2363 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2370 * APIC register must be aligned on 128-bits boundary.
2371 * 32/64/128 bits registers must be accessed thru 32 bits.
2374 if (len != 4 || (offset & 0xf))
2379 kvm_lapic_reg_write(apic, offset & 0xff0, val);
2384 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2386 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2388 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2390 /* emulate APIC access in a trap manner */
2391 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2393 struct kvm_lapic *apic = vcpu->arch.apic;
2397 * ICR is a single 64-bit register when x2APIC is enabled. For legacy
2398 * xAPIC, ICR writes need to go down the common (slightly slower) path
2399 * to get the upper half from ICR2.
2401 if (apic_x2apic_mode(apic) && offset == APIC_ICR) {
2402 val = kvm_lapic_get_reg64(apic, APIC_ICR);
2403 kvm_apic_send_ipi(apic, (u32)val, (u32)(val >> 32));
2404 trace_kvm_apic_write(APIC_ICR, val);
2406 /* TODO: optimize to just emulate side effect w/o one more write */
2407 val = kvm_lapic_get_reg(apic, offset);
2408 kvm_lapic_reg_write(apic, offset, (u32)val);
2411 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2413 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2415 struct kvm_lapic *apic = vcpu->arch.apic;
2417 if (!vcpu->arch.apic)
2420 hrtimer_cancel(&apic->lapic_timer.timer);
2422 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2423 static_branch_slow_dec_deferred(&apic_hw_disabled);
2425 if (!apic->sw_enabled)
2426 static_branch_slow_dec_deferred(&apic_sw_disabled);
2429 free_page((unsigned long)apic->regs);
2435 *----------------------------------------------------------------------
2437 *----------------------------------------------------------------------
2439 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2441 struct kvm_lapic *apic = vcpu->arch.apic;
2443 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2446 return apic->lapic_timer.tscdeadline;
2449 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2451 struct kvm_lapic *apic = vcpu->arch.apic;
2453 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2456 hrtimer_cancel(&apic->lapic_timer.timer);
2457 apic->lapic_timer.tscdeadline = data;
2458 start_apic_timer(apic);
2461 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2463 apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2466 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2470 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2472 return (tpr & 0xf0) >> 4;
2475 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2477 u64 old_value = vcpu->arch.apic_base;
2478 struct kvm_lapic *apic = vcpu->arch.apic;
2480 vcpu->arch.apic_base = value;
2482 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2483 kvm_update_cpuid_runtime(vcpu);
2488 /* update jump label if enable bit changes */
2489 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2490 if (value & MSR_IA32_APICBASE_ENABLE) {
2491 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2492 static_branch_slow_dec_deferred(&apic_hw_disabled);
2493 /* Check if there are APF page ready requests pending */
2494 kvm_make_request(KVM_REQ_APF_READY, vcpu);
2496 static_branch_inc(&apic_hw_disabled.key);
2497 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2501 if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
2502 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2504 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
2505 kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
2506 static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
2509 apic->base_address = apic->vcpu->arch.apic_base &
2510 MSR_IA32_APICBASE_BASE;
2512 if ((value & MSR_IA32_APICBASE_ENABLE) &&
2513 apic->base_address != APIC_DEFAULT_PHYS_BASE) {
2514 kvm_set_apicv_inhibit(apic->vcpu->kvm,
2515 APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
2519 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2521 struct kvm_lapic *apic = vcpu->arch.apic;
2523 if (apic->apicv_active) {
2524 /* irr_pending is always true when apicv is activated. */
2525 apic->irr_pending = true;
2526 apic->isr_count = 1;
2529 * Don't clear irr_pending, searching the IRR can race with
2530 * updates from the CPU as APICv is still active from hardware's
2531 * perspective. The flag will be cleared as appropriate when
2532 * KVM injects the interrupt.
2534 apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2536 apic->highest_isr_cache = -1;
2539 int kvm_alloc_apic_access_page(struct kvm *kvm)
2545 mutex_lock(&kvm->slots_lock);
2546 if (kvm->arch.apic_access_memslot_enabled ||
2547 kvm->arch.apic_access_memslot_inhibited)
2550 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
2551 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
2557 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
2558 if (is_error_page(page)) {
2564 * Do not pin the page in memory, so that memory hot-unplug
2565 * is able to migrate it.
2568 kvm->arch.apic_access_memslot_enabled = true;
2570 mutex_unlock(&kvm->slots_lock);
2573 EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2575 void kvm_inhibit_apic_access_page(struct kvm_vcpu *vcpu)
2577 struct kvm *kvm = vcpu->kvm;
2579 if (!kvm->arch.apic_access_memslot_enabled)
2582 kvm_vcpu_srcu_read_unlock(vcpu);
2584 mutex_lock(&kvm->slots_lock);
2586 if (kvm->arch.apic_access_memslot_enabled) {
2587 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
2589 * Clear "enabled" after the memslot is deleted so that a
2590 * different vCPU doesn't get a false negative when checking
2591 * the flag out of slots_lock. No additional memory barrier is
2592 * needed as modifying memslots requires waiting other vCPUs to
2593 * drop SRCU (see above), and false positives are ok as the
2594 * flag is rechecked after acquiring slots_lock.
2596 kvm->arch.apic_access_memslot_enabled = false;
2599 * Mark the memslot as inhibited to prevent reallocating the
2600 * memslot during vCPU creation, e.g. if a vCPU is hotplugged.
2602 kvm->arch.apic_access_memslot_inhibited = true;
2605 mutex_unlock(&kvm->slots_lock);
2607 kvm_vcpu_srcu_read_lock(vcpu);
2610 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2612 struct kvm_lapic *apic = vcpu->arch.apic;
2617 msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
2618 if (kvm_vcpu_is_reset_bsp(vcpu))
2619 msr_val |= MSR_IA32_APICBASE_BSP;
2620 kvm_lapic_set_base(vcpu, msr_val);
2626 /* Stop the timer in case it's a reset to an active apic */
2627 hrtimer_cancel(&apic->lapic_timer.timer);
2629 /* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2631 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2632 kvm_apic_set_version(apic->vcpu);
2634 for (i = 0; i < apic->nr_lvt_entries; i++)
2635 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2636 apic_update_lvtt(apic);
2637 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2638 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2639 kvm_lapic_set_reg(apic, APIC_LVT0,
2640 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2641 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2643 kvm_apic_set_dfr(apic, 0xffffffffU);
2644 apic_set_spiv(apic, 0xff);
2645 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2646 if (!apic_x2apic_mode(apic))
2647 kvm_apic_set_ldr(apic, 0);
2648 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2649 if (!apic_x2apic_mode(apic)) {
2650 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2651 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2653 kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2655 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2656 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2657 for (i = 0; i < 8; i++) {
2658 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2659 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2660 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2662 kvm_apic_update_apicv(vcpu);
2663 update_divide_count(apic);
2664 atomic_set(&apic->lapic_timer.pending, 0);
2666 vcpu->arch.pv_eoi.msr_val = 0;
2667 apic_update_ppr(apic);
2668 if (apic->apicv_active) {
2669 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2670 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2671 static_call_cond(kvm_x86_hwapic_isr_update)(-1);
2674 vcpu->arch.apic_arb_prio = 0;
2675 vcpu->arch.apic_attention = 0;
2677 kvm_recalculate_apic_map(vcpu->kvm);
2681 *----------------------------------------------------------------------
2683 *----------------------------------------------------------------------
2686 static bool lapic_is_periodic(struct kvm_lapic *apic)
2688 return apic_lvtt_period(apic);
2691 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2693 struct kvm_lapic *apic = vcpu->arch.apic;
2695 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2696 return atomic_read(&apic->lapic_timer.pending);
2701 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2703 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2704 int vector, mode, trig_mode;
2706 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2707 vector = reg & APIC_VECTOR_MASK;
2708 mode = reg & APIC_MODE_MASK;
2709 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2710 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2716 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2718 struct kvm_lapic *apic = vcpu->arch.apic;
2721 kvm_apic_local_deliver(apic, APIC_LVT0);
2724 static const struct kvm_io_device_ops apic_mmio_ops = {
2725 .read = apic_mmio_read,
2726 .write = apic_mmio_write,
2729 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2731 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2732 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2734 apic_timer_expired(apic, true);
2736 if (lapic_is_periodic(apic)) {
2737 advance_periodic_target_expiration(apic);
2738 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2739 return HRTIMER_RESTART;
2741 return HRTIMER_NORESTART;
2744 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2746 struct kvm_lapic *apic;
2748 ASSERT(vcpu != NULL);
2750 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2754 vcpu->arch.apic = apic;
2756 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2758 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2760 goto nomem_free_apic;
2764 apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
2766 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2767 HRTIMER_MODE_ABS_HARD);
2768 apic->lapic_timer.timer.function = apic_timer_fn;
2769 if (timer_advance_ns == -1) {
2770 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2771 lapic_timer_advance_dynamic = true;
2773 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2774 lapic_timer_advance_dynamic = false;
2778 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2779 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2781 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2782 static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2783 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2788 vcpu->arch.apic = NULL;
2793 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2795 struct kvm_lapic *apic = vcpu->arch.apic;
2798 if (!kvm_apic_present(vcpu))
2801 __apic_update_ppr(apic, &ppr);
2802 return apic_has_interrupt_for_ppr(apic, ppr);
2804 EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2806 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2808 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2810 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2812 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2813 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2818 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2820 struct kvm_lapic *apic = vcpu->arch.apic;
2822 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2823 kvm_apic_inject_pending_timer_irqs(apic);
2824 atomic_set(&apic->lapic_timer.pending, 0);
2828 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2830 int vector = kvm_apic_has_interrupt(vcpu);
2831 struct kvm_lapic *apic = vcpu->arch.apic;
2838 * We get here even with APIC virtualization enabled, if doing
2839 * nested virtualization and L1 runs with the "acknowledge interrupt
2840 * on exit" mode. Then we cannot inject the interrupt via RVI,
2841 * because the process would deliver it through the IDT.
2844 apic_clear_irr(vector, apic);
2845 if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
2847 * For auto-EOI interrupts, there might be another pending
2848 * interrupt above PPR, so check whether to raise another
2851 apic_update_ppr(apic);
2854 * For normal interrupts, PPR has been raised and there cannot
2855 * be a higher-priority pending interrupt---except if there was
2856 * a concurrent interrupt injection, but that would have
2857 * triggered KVM_REQ_EVENT already.
2859 apic_set_isr(vector, apic);
2860 __apic_update_ppr(apic, &ppr);
2866 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2867 struct kvm_lapic_state *s, bool set)
2869 if (apic_x2apic_mode(vcpu->arch.apic)) {
2870 u32 *id = (u32 *)(s->regs + APIC_ID);
2871 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2874 if (vcpu->kvm->arch.x2apic_format) {
2875 if (*id != vcpu->vcpu_id)
2885 * In x2APIC mode, the LDR is fixed and based on the id. And
2886 * ICR is internally a single 64-bit register, but needs to be
2887 * split to ICR+ICR2 in userspace for backwards compatibility.
2890 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2892 icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
2893 (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
2894 __kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
2896 icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
2897 __kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
2904 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2906 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2909 * Get calculated timer current count for remaining timer period (if
2910 * any) and store it in the returned register set.
2912 __kvm_lapic_set_reg(s->regs, APIC_TMCCT,
2913 __apic_read(vcpu->arch.apic, APIC_TMCCT));
2915 return kvm_apic_state_fixup(vcpu, s, false);
2918 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2920 struct kvm_lapic *apic = vcpu->arch.apic;
2923 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2924 /* set SPIV separately to get count of SW disabled APICs right */
2925 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2927 r = kvm_apic_state_fixup(vcpu, s, true);
2929 kvm_recalculate_apic_map(vcpu->kvm);
2932 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2934 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2935 kvm_recalculate_apic_map(vcpu->kvm);
2936 kvm_apic_set_version(vcpu);
2938 apic_update_ppr(apic);
2939 cancel_apic_timer(apic);
2940 apic->lapic_timer.expired_tscdeadline = 0;
2941 apic_update_lvtt(apic);
2942 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2943 update_divide_count(apic);
2944 __start_apic_timer(apic, APIC_TMCCT);
2945 kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
2946 kvm_apic_update_apicv(vcpu);
2947 if (apic->apicv_active) {
2948 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2949 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
2950 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
2952 kvm_make_request(KVM_REQ_EVENT, vcpu);
2953 if (ioapic_in_kernel(vcpu->kvm))
2954 kvm_rtc_eoi_tracking_restore_one(vcpu);
2956 vcpu->arch.apic_arb_prio = 0;
2961 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2963 struct hrtimer *timer;
2965 if (!lapic_in_kernel(vcpu) ||
2966 kvm_can_post_timer_interrupt(vcpu))
2969 timer = &vcpu->arch.apic->lapic_timer.timer;
2970 if (hrtimer_cancel(timer))
2971 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2975 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2977 * Detect whether guest triggered PV EOI since the
2978 * last entry. If yes, set EOI on guests's behalf.
2979 * Clear PV EOI in guest memory in any case.
2981 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2982 struct kvm_lapic *apic)
2986 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2987 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2989 * KVM_APIC_PV_EOI_PENDING is unset:
2990 * -> host disabled PV EOI.
2991 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2992 * -> host enabled PV EOI, guest did not execute EOI yet.
2993 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2994 * -> host enabled PV EOI, guest executed EOI.
2996 BUG_ON(!pv_eoi_enabled(vcpu));
2998 if (pv_eoi_test_and_clr_pending(vcpu))
3000 vector = apic_set_eoi(apic);
3001 trace_kvm_pv_eoi(apic, vector);
3004 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3008 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
3009 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
3011 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3014 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3018 apic_set_tpr(vcpu->arch.apic, data & 0xff);
3022 * apic_sync_pv_eoi_to_guest - called before vmentry
3024 * Detect whether it's safe to enable PV EOI and
3027 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
3028 struct kvm_lapic *apic)
3030 if (!pv_eoi_enabled(vcpu) ||
3031 /* IRR set or many bits in ISR: could be nested. */
3032 apic->irr_pending ||
3033 /* Cache not set: could be safe but we don't bother. */
3034 apic->highest_isr_cache == -1 ||
3035 /* Need EOI to update ioapic. */
3036 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
3038 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
3039 * so we need not do anything here.
3044 pv_eoi_set_pending(apic->vcpu);
3047 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3050 int max_irr, max_isr;
3051 struct kvm_lapic *apic = vcpu->arch.apic;
3053 apic_sync_pv_eoi_to_guest(vcpu, apic);
3055 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3058 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
3059 max_irr = apic_find_highest_irr(apic);
3062 max_isr = apic_find_highest_isr(apic);
3065 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
3067 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3071 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
3074 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
3075 &vcpu->arch.apic->vapic_cache,
3076 vapic_addr, sizeof(u32)))
3078 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3080 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3083 vcpu->arch.apic->vapic_addr = vapic_addr;
3087 int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
3089 data &= ~APIC_ICR_BUSY;
3091 kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
3092 kvm_lapic_set_reg64(apic, APIC_ICR, data);
3093 trace_kvm_apic_write(APIC_ICR, data);
3097 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
3101 if (reg == APIC_ICR) {
3102 *data = kvm_lapic_get_reg64(apic, APIC_ICR);
3106 if (kvm_lapic_reg_read(apic, reg, 4, &low))
3114 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
3117 * ICR is a 64-bit register in x2APIC mode (and Hyper'v PV vAPIC) and
3118 * can be written as such, all other registers remain accessible only
3119 * through 32-bit reads/writes.
3121 if (reg == APIC_ICR)
3122 return kvm_x2apic_icr_write(apic, data);
3124 return kvm_lapic_reg_write(apic, reg, (u32)data);
3127 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
3129 struct kvm_lapic *apic = vcpu->arch.apic;
3130 u32 reg = (msr - APIC_BASE_MSR) << 4;
3132 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3135 return kvm_lapic_msr_write(apic, reg, data);
3138 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
3140 struct kvm_lapic *apic = vcpu->arch.apic;
3141 u32 reg = (msr - APIC_BASE_MSR) << 4;
3143 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3146 if (reg == APIC_DFR)
3149 return kvm_lapic_msr_read(apic, reg, data);
3152 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
3154 if (!lapic_in_kernel(vcpu))
3157 return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
3160 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
3162 if (!lapic_in_kernel(vcpu))
3165 return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
3168 int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3170 u64 addr = data & ~KVM_MSR_ENABLED;
3171 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3172 unsigned long new_len;
3175 if (!IS_ALIGNED(addr, 4))
3178 if (data & KVM_MSR_ENABLED) {
3179 if (addr == ghc->gpa && len <= ghc->len)
3184 ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3189 vcpu->arch.pv_eoi.msr_val = data;
3194 int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
3196 struct kvm_lapic *apic = vcpu->arch.apic;
3200 if (!kvm_apic_has_pending_init_or_sipi(vcpu))
3203 if (is_guest_mode(vcpu)) {
3204 r = kvm_check_nested_events(vcpu);
3206 return r == -EBUSY ? 0 : r;
3208 * Continue processing INIT/SIPI even if a nested VM-Exit
3209 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
3210 * are blocked as a result of transitioning to VMX root mode.
3215 * INITs are blocked while CPU is in specific states (SMM, VMX root
3216 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
3217 * wait-for-SIPI (WFS).
3219 if (!kvm_apic_init_sipi_allowed(vcpu)) {
3220 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3221 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
3225 if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3226 kvm_vcpu_reset(vcpu, true);
3227 if (kvm_vcpu_is_bsp(apic->vcpu))
3228 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3230 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
3232 if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3233 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
3234 /* evaluate pending_events before reading the vector */
3236 sipi_vector = apic->sipi_vector;
3237 static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
3238 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3244 void kvm_lapic_exit(void)
3246 static_key_deferred_flush(&apic_hw_disabled);
3247 WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3248 static_key_deferred_flush(&apic_sw_disabled);
3249 WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));