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 u64 kvm_lapic_readable_reg_mask(struct kvm_lapic *apic)
1566 /* Leave bits '0' for reserved and write-only registers. */
1567 u64 valid_reg_mask =
1568 APIC_REG_MASK(APIC_ID) |
1569 APIC_REG_MASK(APIC_LVR) |
1570 APIC_REG_MASK(APIC_TASKPRI) |
1571 APIC_REG_MASK(APIC_PROCPRI) |
1572 APIC_REG_MASK(APIC_LDR) |
1573 APIC_REG_MASK(APIC_SPIV) |
1574 APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1575 APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1576 APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1577 APIC_REG_MASK(APIC_ESR) |
1578 APIC_REG_MASK(APIC_ICR) |
1579 APIC_REG_MASK(APIC_LVTT) |
1580 APIC_REG_MASK(APIC_LVTTHMR) |
1581 APIC_REG_MASK(APIC_LVTPC) |
1582 APIC_REG_MASK(APIC_LVT0) |
1583 APIC_REG_MASK(APIC_LVT1) |
1584 APIC_REG_MASK(APIC_LVTERR) |
1585 APIC_REG_MASK(APIC_TMICT) |
1586 APIC_REG_MASK(APIC_TMCCT) |
1587 APIC_REG_MASK(APIC_TDCR);
1589 if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
1590 valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
1592 /* ARBPRI, DFR, and ICR2 are not valid in x2APIC mode. */
1593 if (!apic_x2apic_mode(apic))
1594 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1595 APIC_REG_MASK(APIC_DFR) |
1596 APIC_REG_MASK(APIC_ICR2);
1598 return valid_reg_mask;
1600 EXPORT_SYMBOL_GPL(kvm_lapic_readable_reg_mask);
1602 static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1605 unsigned char alignment = offset & 0xf;
1609 * WARN if KVM reads ICR in x2APIC mode, as it's an 8-byte register in
1610 * x2APIC and needs to be manually handled by the caller.
1612 WARN_ON_ONCE(apic_x2apic_mode(apic) && offset == APIC_ICR);
1614 if (alignment + len > 4)
1617 if (offset > 0x3f0 ||
1618 !(kvm_lapic_readable_reg_mask(apic) & APIC_REG_MASK(offset)))
1621 result = __apic_read(apic, offset & ~0xf);
1623 trace_kvm_apic_read(offset, result);
1629 memcpy(data, (char *)&result + alignment, len);
1632 printk(KERN_ERR "Local APIC read with len = %x, "
1633 "should be 1,2, or 4 instead\n", len);
1639 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1641 return addr >= apic->base_address &&
1642 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1645 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1646 gpa_t address, int len, void *data)
1648 struct kvm_lapic *apic = to_lapic(this);
1649 u32 offset = address - apic->base_address;
1651 if (!apic_mmio_in_range(apic, address))
1654 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1655 if (!kvm_check_has_quirk(vcpu->kvm,
1656 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1659 memset(data, 0xff, len);
1663 kvm_lapic_reg_read(apic, offset, len, data);
1668 static void update_divide_count(struct kvm_lapic *apic)
1670 u32 tmp1, tmp2, tdcr;
1672 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1674 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1675 apic->divide_count = 0x1 << (tmp2 & 0x7);
1678 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1681 * Do not allow the guest to program periodic timers with small
1682 * interval, since the hrtimers are not throttled by the host
1685 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1686 s64 min_period = min_timer_period_us * 1000LL;
1688 if (apic->lapic_timer.period < min_period) {
1689 pr_info_ratelimited(
1690 "vcpu %i: requested %lld ns "
1691 "lapic timer period limited to %lld ns\n",
1692 apic->vcpu->vcpu_id,
1693 apic->lapic_timer.period, min_period);
1694 apic->lapic_timer.period = min_period;
1699 static void cancel_hv_timer(struct kvm_lapic *apic);
1701 static void cancel_apic_timer(struct kvm_lapic *apic)
1703 hrtimer_cancel(&apic->lapic_timer.timer);
1705 if (apic->lapic_timer.hv_timer_in_use)
1706 cancel_hv_timer(apic);
1708 atomic_set(&apic->lapic_timer.pending, 0);
1711 static void apic_update_lvtt(struct kvm_lapic *apic)
1713 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1714 apic->lapic_timer.timer_mode_mask;
1716 if (apic->lapic_timer.timer_mode != timer_mode) {
1717 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1718 APIC_LVT_TIMER_TSCDEADLINE)) {
1719 cancel_apic_timer(apic);
1720 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1721 apic->lapic_timer.period = 0;
1722 apic->lapic_timer.tscdeadline = 0;
1724 apic->lapic_timer.timer_mode = timer_mode;
1725 limit_periodic_timer_frequency(apic);
1730 * On APICv, this test will cause a busy wait
1731 * during a higher-priority task.
1734 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1736 struct kvm_lapic *apic = vcpu->arch.apic;
1737 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1739 if (kvm_apic_hw_enabled(apic)) {
1740 int vec = reg & APIC_VECTOR_MASK;
1741 void *bitmap = apic->regs + APIC_ISR;
1743 if (apic->apicv_active)
1744 bitmap = apic->regs + APIC_IRR;
1746 if (apic_test_vector(vec, bitmap))
1752 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1754 u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1757 * If the guest TSC is running at a different ratio than the host, then
1758 * convert the delay to nanoseconds to achieve an accurate delay. Note
1759 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1760 * always for VMX enabled hardware.
1762 if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1763 __delay(min(guest_cycles,
1764 nsec_to_cycles(vcpu, timer_advance_ns)));
1766 u64 delay_ns = guest_cycles * 1000000ULL;
1767 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1768 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1772 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1773 s64 advance_expire_delta)
1775 struct kvm_lapic *apic = vcpu->arch.apic;
1776 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1779 /* Do not adjust for tiny fluctuations or large random spikes. */
1780 if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1781 abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1785 if (advance_expire_delta < 0) {
1786 ns = -advance_expire_delta * 1000000ULL;
1787 do_div(ns, vcpu->arch.virtual_tsc_khz);
1788 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1791 ns = advance_expire_delta * 1000000ULL;
1792 do_div(ns, vcpu->arch.virtual_tsc_khz);
1793 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1796 if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1797 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1798 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1801 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1803 struct kvm_lapic *apic = vcpu->arch.apic;
1804 u64 guest_tsc, tsc_deadline;
1806 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1807 apic->lapic_timer.expired_tscdeadline = 0;
1808 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1809 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1811 if (lapic_timer_advance_dynamic) {
1812 adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
1814 * If the timer fired early, reread the TSC to account for the
1815 * overhead of the above adjustment to avoid waiting longer
1816 * than is necessary.
1818 if (guest_tsc < tsc_deadline)
1819 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1822 if (guest_tsc < tsc_deadline)
1823 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1826 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1828 if (lapic_in_kernel(vcpu) &&
1829 vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1830 vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1831 lapic_timer_int_injected(vcpu))
1832 __kvm_wait_lapic_expire(vcpu);
1834 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1836 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1838 struct kvm_timer *ktimer = &apic->lapic_timer;
1840 kvm_apic_local_deliver(apic, APIC_LVTT);
1841 if (apic_lvtt_tscdeadline(apic)) {
1842 ktimer->tscdeadline = 0;
1843 } else if (apic_lvtt_oneshot(apic)) {
1844 ktimer->tscdeadline = 0;
1845 ktimer->target_expiration = 0;
1849 static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
1851 struct kvm_vcpu *vcpu = apic->vcpu;
1852 struct kvm_timer *ktimer = &apic->lapic_timer;
1854 if (atomic_read(&apic->lapic_timer.pending))
1857 if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1858 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1860 if (!from_timer_fn && apic->apicv_active) {
1861 WARN_ON(kvm_get_running_vcpu() != vcpu);
1862 kvm_apic_inject_pending_timer_irqs(apic);
1866 if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1868 * Ensure the guest's timer has truly expired before posting an
1869 * interrupt. Open code the relevant checks to avoid querying
1870 * lapic_timer_int_injected(), which will be false since the
1871 * interrupt isn't yet injected. Waiting until after injecting
1872 * is not an option since that won't help a posted interrupt.
1874 if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1875 vcpu->arch.apic->lapic_timer.timer_advance_ns)
1876 __kvm_wait_lapic_expire(vcpu);
1877 kvm_apic_inject_pending_timer_irqs(apic);
1881 atomic_inc(&apic->lapic_timer.pending);
1882 kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1884 kvm_vcpu_kick(vcpu);
1887 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1889 struct kvm_timer *ktimer = &apic->lapic_timer;
1890 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1893 struct kvm_vcpu *vcpu = apic->vcpu;
1894 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1895 unsigned long flags;
1898 if (unlikely(!tscdeadline || !this_tsc_khz))
1901 local_irq_save(flags);
1904 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1906 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1907 do_div(ns, this_tsc_khz);
1909 if (likely(tscdeadline > guest_tsc) &&
1910 likely(ns > apic->lapic_timer.timer_advance_ns)) {
1911 expire = ktime_add_ns(now, ns);
1912 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1913 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1915 apic_timer_expired(apic, false);
1917 local_irq_restore(flags);
1920 static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1922 return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
1925 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1927 ktime_t now, remaining;
1928 u64 ns_remaining_old, ns_remaining_new;
1930 apic->lapic_timer.period =
1931 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1932 limit_periodic_timer_frequency(apic);
1935 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1936 if (ktime_to_ns(remaining) < 0)
1939 ns_remaining_old = ktime_to_ns(remaining);
1940 ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1941 apic->divide_count, old_divisor);
1943 apic->lapic_timer.tscdeadline +=
1944 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1945 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1946 apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1949 static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1956 apic->lapic_timer.period =
1957 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1959 if (!apic->lapic_timer.period) {
1960 apic->lapic_timer.tscdeadline = 0;
1964 limit_periodic_timer_frequency(apic);
1965 deadline = apic->lapic_timer.period;
1967 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1968 if (unlikely(count_reg != APIC_TMICT)) {
1969 deadline = tmict_to_ns(apic,
1970 kvm_lapic_get_reg(apic, count_reg));
1971 if (unlikely(deadline <= 0)) {
1972 if (apic_lvtt_period(apic))
1973 deadline = apic->lapic_timer.period;
1977 else if (unlikely(deadline > apic->lapic_timer.period)) {
1978 pr_info_ratelimited(
1979 "vcpu %i: requested lapic timer restore with "
1980 "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
1981 "Using initial count to start timer.\n",
1982 apic->vcpu->vcpu_id,
1984 kvm_lapic_get_reg(apic, count_reg),
1985 deadline, apic->lapic_timer.period);
1986 kvm_lapic_set_reg(apic, count_reg, 0);
1987 deadline = apic->lapic_timer.period;
1992 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1993 nsec_to_cycles(apic->vcpu, deadline);
1994 apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
1999 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
2001 ktime_t now = ktime_get();
2006 * Synchronize both deadlines to the same time source or
2007 * differences in the periods (caused by differences in the
2008 * underlying clocks or numerical approximation errors) will
2009 * cause the two to drift apart over time as the errors
2012 apic->lapic_timer.target_expiration =
2013 ktime_add_ns(apic->lapic_timer.target_expiration,
2014 apic->lapic_timer.period);
2015 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
2016 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
2017 nsec_to_cycles(apic->vcpu, delta);
2020 static void start_sw_period(struct kvm_lapic *apic)
2022 if (!apic->lapic_timer.period)
2025 if (ktime_after(ktime_get(),
2026 apic->lapic_timer.target_expiration)) {
2027 apic_timer_expired(apic, false);
2029 if (apic_lvtt_oneshot(apic))
2032 advance_periodic_target_expiration(apic);
2035 hrtimer_start(&apic->lapic_timer.timer,
2036 apic->lapic_timer.target_expiration,
2037 HRTIMER_MODE_ABS_HARD);
2040 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2042 if (!lapic_in_kernel(vcpu))
2045 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2048 static void cancel_hv_timer(struct kvm_lapic *apic)
2050 WARN_ON(preemptible());
2051 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2052 static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
2053 apic->lapic_timer.hv_timer_in_use = false;
2056 static bool start_hv_timer(struct kvm_lapic *apic)
2058 struct kvm_timer *ktimer = &apic->lapic_timer;
2059 struct kvm_vcpu *vcpu = apic->vcpu;
2062 WARN_ON(preemptible());
2063 if (!kvm_can_use_hv_timer(vcpu))
2066 if (!ktimer->tscdeadline)
2069 if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
2072 ktimer->hv_timer_in_use = true;
2073 hrtimer_cancel(&ktimer->timer);
2076 * To simplify handling the periodic timer, leave the hv timer running
2077 * even if the deadline timer has expired, i.e. rely on the resulting
2078 * VM-Exit to recompute the periodic timer's target expiration.
2080 if (!apic_lvtt_period(apic)) {
2082 * Cancel the hv timer if the sw timer fired while the hv timer
2083 * was being programmed, or if the hv timer itself expired.
2085 if (atomic_read(&ktimer->pending)) {
2086 cancel_hv_timer(apic);
2087 } else if (expired) {
2088 apic_timer_expired(apic, false);
2089 cancel_hv_timer(apic);
2093 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
2098 static void start_sw_timer(struct kvm_lapic *apic)
2100 struct kvm_timer *ktimer = &apic->lapic_timer;
2102 WARN_ON(preemptible());
2103 if (apic->lapic_timer.hv_timer_in_use)
2104 cancel_hv_timer(apic);
2105 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
2108 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2109 start_sw_period(apic);
2110 else if (apic_lvtt_tscdeadline(apic))
2111 start_sw_tscdeadline(apic);
2112 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
2115 static void restart_apic_timer(struct kvm_lapic *apic)
2119 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
2122 if (!start_hv_timer(apic))
2123 start_sw_timer(apic);
2128 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
2130 struct kvm_lapic *apic = vcpu->arch.apic;
2133 /* If the preempt notifier has already run, it also called apic_timer_expired */
2134 if (!apic->lapic_timer.hv_timer_in_use)
2136 WARN_ON(kvm_vcpu_is_blocking(vcpu));
2137 apic_timer_expired(apic, false);
2138 cancel_hv_timer(apic);
2140 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
2141 advance_periodic_target_expiration(apic);
2142 restart_apic_timer(apic);
2147 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
2149 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2151 restart_apic_timer(vcpu->arch.apic);
2154 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2156 struct kvm_lapic *apic = vcpu->arch.apic;
2159 /* Possibly the TSC deadline timer is not enabled yet */
2160 if (apic->lapic_timer.hv_timer_in_use)
2161 start_sw_timer(apic);
2165 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2167 struct kvm_lapic *apic = vcpu->arch.apic;
2169 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2170 restart_apic_timer(apic);
2173 static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2175 atomic_set(&apic->lapic_timer.pending, 0);
2177 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2178 && !set_target_expiration(apic, count_reg))
2181 restart_apic_timer(apic);
2184 static void start_apic_timer(struct kvm_lapic *apic)
2186 __start_apic_timer(apic, APIC_TMICT);
2189 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2191 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2193 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
2194 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
2195 if (lvt0_in_nmi_mode) {
2196 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2198 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2202 static int get_lvt_index(u32 reg)
2204 if (reg == APIC_LVTCMCI)
2206 if (reg < APIC_LVTT || reg > APIC_LVTERR)
2208 return array_index_nospec(
2209 (reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
2212 static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2216 trace_kvm_apic_write(reg, val);
2219 case APIC_ID: /* Local APIC ID */
2220 if (!apic_x2apic_mode(apic)) {
2221 kvm_apic_set_xapic_id(apic, val >> 24);
2228 report_tpr_access(apic, true);
2229 apic_set_tpr(apic, val & 0xff);
2237 if (!apic_x2apic_mode(apic))
2238 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
2244 if (!apic_x2apic_mode(apic))
2245 kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2252 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2253 mask |= APIC_SPIV_DIRECTED_EOI;
2254 apic_set_spiv(apic, val & mask);
2255 if (!(val & APIC_SPIV_APIC_ENABLED)) {
2258 for (i = 0; i < apic->nr_lvt_entries; i++) {
2259 kvm_lapic_set_reg(apic, APIC_LVTx(i),
2260 kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2262 apic_update_lvtt(apic);
2263 atomic_set(&apic->lapic_timer.pending, 0);
2269 WARN_ON_ONCE(apic_x2apic_mode(apic));
2271 /* No delay here, so we always clear the pending bit */
2272 val &= ~APIC_ICR_BUSY;
2273 kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2274 kvm_lapic_set_reg(apic, APIC_ICR, val);
2277 if (apic_x2apic_mode(apic))
2280 kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2284 apic_manage_nmi_watchdog(apic, val);
2290 case APIC_LVTCMCI: {
2291 u32 index = get_lvt_index(reg);
2292 if (!kvm_lapic_lvt_supported(apic, index)) {
2296 if (!kvm_apic_sw_enabled(apic))
2297 val |= APIC_LVT_MASKED;
2298 val &= apic_lvt_mask[index];
2299 kvm_lapic_set_reg(apic, reg, val);
2304 if (!kvm_apic_sw_enabled(apic))
2305 val |= APIC_LVT_MASKED;
2306 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
2307 kvm_lapic_set_reg(apic, APIC_LVTT, val);
2308 apic_update_lvtt(apic);
2312 if (apic_lvtt_tscdeadline(apic))
2315 cancel_apic_timer(apic);
2316 kvm_lapic_set_reg(apic, APIC_TMICT, val);
2317 start_apic_timer(apic);
2321 uint32_t old_divisor = apic->divide_count;
2323 kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2324 update_divide_count(apic);
2325 if (apic->divide_count != old_divisor &&
2326 apic->lapic_timer.period) {
2327 hrtimer_cancel(&apic->lapic_timer.timer);
2328 update_target_expiration(apic, old_divisor);
2329 restart_apic_timer(apic);
2334 if (apic_x2apic_mode(apic) && val != 0)
2340 * Self-IPI exists only when x2APIC is enabled. Bits 7:0 hold
2341 * the vector, everything else is reserved.
2343 if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
2346 kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
2354 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2355 * was toggled, the APIC ID changed, etc... The maps are marked dirty
2356 * on relevant changes, i.e. this is a nop for most writes.
2358 kvm_recalculate_apic_map(apic->vcpu->kvm);
2363 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2364 gpa_t address, int len, const void *data)
2366 struct kvm_lapic *apic = to_lapic(this);
2367 unsigned int offset = address - apic->base_address;
2370 if (!apic_mmio_in_range(apic, address))
2373 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2374 if (!kvm_check_has_quirk(vcpu->kvm,
2375 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2382 * APIC register must be aligned on 128-bits boundary.
2383 * 32/64/128 bits registers must be accessed thru 32 bits.
2386 if (len != 4 || (offset & 0xf))
2391 kvm_lapic_reg_write(apic, offset & 0xff0, val);
2396 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2398 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2400 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2402 /* emulate APIC access in a trap manner */
2403 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2405 struct kvm_lapic *apic = vcpu->arch.apic;
2409 * ICR is a single 64-bit register when x2APIC is enabled. For legacy
2410 * xAPIC, ICR writes need to go down the common (slightly slower) path
2411 * to get the upper half from ICR2.
2413 if (apic_x2apic_mode(apic) && offset == APIC_ICR) {
2414 val = kvm_lapic_get_reg64(apic, APIC_ICR);
2415 kvm_apic_send_ipi(apic, (u32)val, (u32)(val >> 32));
2416 trace_kvm_apic_write(APIC_ICR, val);
2418 /* TODO: optimize to just emulate side effect w/o one more write */
2419 val = kvm_lapic_get_reg(apic, offset);
2420 kvm_lapic_reg_write(apic, offset, (u32)val);
2423 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2425 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2427 struct kvm_lapic *apic = vcpu->arch.apic;
2429 if (!vcpu->arch.apic)
2432 hrtimer_cancel(&apic->lapic_timer.timer);
2434 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2435 static_branch_slow_dec_deferred(&apic_hw_disabled);
2437 if (!apic->sw_enabled)
2438 static_branch_slow_dec_deferred(&apic_sw_disabled);
2441 free_page((unsigned long)apic->regs);
2447 *----------------------------------------------------------------------
2449 *----------------------------------------------------------------------
2451 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2453 struct kvm_lapic *apic = vcpu->arch.apic;
2455 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2458 return apic->lapic_timer.tscdeadline;
2461 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2463 struct kvm_lapic *apic = vcpu->arch.apic;
2465 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2468 hrtimer_cancel(&apic->lapic_timer.timer);
2469 apic->lapic_timer.tscdeadline = data;
2470 start_apic_timer(apic);
2473 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2475 apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2478 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2482 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2484 return (tpr & 0xf0) >> 4;
2487 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2489 u64 old_value = vcpu->arch.apic_base;
2490 struct kvm_lapic *apic = vcpu->arch.apic;
2492 vcpu->arch.apic_base = value;
2494 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2495 kvm_update_cpuid_runtime(vcpu);
2500 /* update jump label if enable bit changes */
2501 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2502 if (value & MSR_IA32_APICBASE_ENABLE) {
2503 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2504 static_branch_slow_dec_deferred(&apic_hw_disabled);
2505 /* Check if there are APF page ready requests pending */
2506 kvm_make_request(KVM_REQ_APF_READY, vcpu);
2508 static_branch_inc(&apic_hw_disabled.key);
2509 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2513 if ((old_value ^ value) & X2APIC_ENABLE) {
2514 if (value & X2APIC_ENABLE)
2515 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2516 else if (value & MSR_IA32_APICBASE_ENABLE)
2517 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2520 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
2521 kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
2522 static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
2525 apic->base_address = apic->vcpu->arch.apic_base &
2526 MSR_IA32_APICBASE_BASE;
2528 if ((value & MSR_IA32_APICBASE_ENABLE) &&
2529 apic->base_address != APIC_DEFAULT_PHYS_BASE) {
2530 kvm_set_apicv_inhibit(apic->vcpu->kvm,
2531 APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
2535 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2537 struct kvm_lapic *apic = vcpu->arch.apic;
2539 if (apic->apicv_active) {
2540 /* irr_pending is always true when apicv is activated. */
2541 apic->irr_pending = true;
2542 apic->isr_count = 1;
2545 * Don't clear irr_pending, searching the IRR can race with
2546 * updates from the CPU as APICv is still active from hardware's
2547 * perspective. The flag will be cleared as appropriate when
2548 * KVM injects the interrupt.
2550 apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2552 apic->highest_isr_cache = -1;
2555 int kvm_alloc_apic_access_page(struct kvm *kvm)
2561 mutex_lock(&kvm->slots_lock);
2562 if (kvm->arch.apic_access_memslot_enabled ||
2563 kvm->arch.apic_access_memslot_inhibited)
2566 hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
2567 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
2573 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
2574 if (is_error_page(page)) {
2580 * Do not pin the page in memory, so that memory hot-unplug
2581 * is able to migrate it.
2584 kvm->arch.apic_access_memslot_enabled = true;
2586 mutex_unlock(&kvm->slots_lock);
2589 EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2591 void kvm_inhibit_apic_access_page(struct kvm_vcpu *vcpu)
2593 struct kvm *kvm = vcpu->kvm;
2595 if (!kvm->arch.apic_access_memslot_enabled)
2598 kvm_vcpu_srcu_read_unlock(vcpu);
2600 mutex_lock(&kvm->slots_lock);
2602 if (kvm->arch.apic_access_memslot_enabled) {
2603 __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
2605 * Clear "enabled" after the memslot is deleted so that a
2606 * different vCPU doesn't get a false negative when checking
2607 * the flag out of slots_lock. No additional memory barrier is
2608 * needed as modifying memslots requires waiting other vCPUs to
2609 * drop SRCU (see above), and false positives are ok as the
2610 * flag is rechecked after acquiring slots_lock.
2612 kvm->arch.apic_access_memslot_enabled = false;
2615 * Mark the memslot as inhibited to prevent reallocating the
2616 * memslot during vCPU creation, e.g. if a vCPU is hotplugged.
2618 kvm->arch.apic_access_memslot_inhibited = true;
2621 mutex_unlock(&kvm->slots_lock);
2623 kvm_vcpu_srcu_read_lock(vcpu);
2626 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2628 struct kvm_lapic *apic = vcpu->arch.apic;
2633 msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
2634 if (kvm_vcpu_is_reset_bsp(vcpu))
2635 msr_val |= MSR_IA32_APICBASE_BSP;
2636 kvm_lapic_set_base(vcpu, msr_val);
2642 /* Stop the timer in case it's a reset to an active apic */
2643 hrtimer_cancel(&apic->lapic_timer.timer);
2645 /* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2647 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2648 kvm_apic_set_version(apic->vcpu);
2650 for (i = 0; i < apic->nr_lvt_entries; i++)
2651 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2652 apic_update_lvtt(apic);
2653 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2654 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2655 kvm_lapic_set_reg(apic, APIC_LVT0,
2656 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2657 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2659 kvm_apic_set_dfr(apic, 0xffffffffU);
2660 apic_set_spiv(apic, 0xff);
2661 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2662 if (!apic_x2apic_mode(apic))
2663 kvm_apic_set_ldr(apic, 0);
2664 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2665 if (!apic_x2apic_mode(apic)) {
2666 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2667 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2669 kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2671 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2672 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2673 for (i = 0; i < 8; i++) {
2674 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2675 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2676 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2678 kvm_apic_update_apicv(vcpu);
2679 update_divide_count(apic);
2680 atomic_set(&apic->lapic_timer.pending, 0);
2682 vcpu->arch.pv_eoi.msr_val = 0;
2683 apic_update_ppr(apic);
2684 if (apic->apicv_active) {
2685 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2686 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2687 static_call_cond(kvm_x86_hwapic_isr_update)(-1);
2690 vcpu->arch.apic_arb_prio = 0;
2691 vcpu->arch.apic_attention = 0;
2693 kvm_recalculate_apic_map(vcpu->kvm);
2697 *----------------------------------------------------------------------
2699 *----------------------------------------------------------------------
2702 static bool lapic_is_periodic(struct kvm_lapic *apic)
2704 return apic_lvtt_period(apic);
2707 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2709 struct kvm_lapic *apic = vcpu->arch.apic;
2711 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2712 return atomic_read(&apic->lapic_timer.pending);
2717 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2719 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2720 int vector, mode, trig_mode;
2722 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2723 vector = reg & APIC_VECTOR_MASK;
2724 mode = reg & APIC_MODE_MASK;
2725 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2726 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2732 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2734 struct kvm_lapic *apic = vcpu->arch.apic;
2737 kvm_apic_local_deliver(apic, APIC_LVT0);
2740 static const struct kvm_io_device_ops apic_mmio_ops = {
2741 .read = apic_mmio_read,
2742 .write = apic_mmio_write,
2745 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2747 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2748 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2750 apic_timer_expired(apic, true);
2752 if (lapic_is_periodic(apic)) {
2753 advance_periodic_target_expiration(apic);
2754 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2755 return HRTIMER_RESTART;
2757 return HRTIMER_NORESTART;
2760 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2762 struct kvm_lapic *apic;
2764 ASSERT(vcpu != NULL);
2766 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2770 vcpu->arch.apic = apic;
2772 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2774 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2776 goto nomem_free_apic;
2780 apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
2782 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2783 HRTIMER_MODE_ABS_HARD);
2784 apic->lapic_timer.timer.function = apic_timer_fn;
2785 if (timer_advance_ns == -1) {
2786 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2787 lapic_timer_advance_dynamic = true;
2789 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2790 lapic_timer_advance_dynamic = false;
2794 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2795 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2797 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2798 static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2799 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2804 vcpu->arch.apic = NULL;
2809 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2811 struct kvm_lapic *apic = vcpu->arch.apic;
2814 if (!kvm_apic_present(vcpu))
2817 __apic_update_ppr(apic, &ppr);
2818 return apic_has_interrupt_for_ppr(apic, ppr);
2820 EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2822 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2824 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2826 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2828 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2829 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2834 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2836 struct kvm_lapic *apic = vcpu->arch.apic;
2838 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2839 kvm_apic_inject_pending_timer_irqs(apic);
2840 atomic_set(&apic->lapic_timer.pending, 0);
2844 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2846 int vector = kvm_apic_has_interrupt(vcpu);
2847 struct kvm_lapic *apic = vcpu->arch.apic;
2854 * We get here even with APIC virtualization enabled, if doing
2855 * nested virtualization and L1 runs with the "acknowledge interrupt
2856 * on exit" mode. Then we cannot inject the interrupt via RVI,
2857 * because the process would deliver it through the IDT.
2860 apic_clear_irr(vector, apic);
2861 if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
2863 * For auto-EOI interrupts, there might be another pending
2864 * interrupt above PPR, so check whether to raise another
2867 apic_update_ppr(apic);
2870 * For normal interrupts, PPR has been raised and there cannot
2871 * be a higher-priority pending interrupt---except if there was
2872 * a concurrent interrupt injection, but that would have
2873 * triggered KVM_REQ_EVENT already.
2875 apic_set_isr(vector, apic);
2876 __apic_update_ppr(apic, &ppr);
2882 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2883 struct kvm_lapic_state *s, bool set)
2885 if (apic_x2apic_mode(vcpu->arch.apic)) {
2886 u32 *id = (u32 *)(s->regs + APIC_ID);
2887 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2890 if (vcpu->kvm->arch.x2apic_format) {
2891 if (*id != vcpu->vcpu_id)
2901 * In x2APIC mode, the LDR is fixed and based on the id. And
2902 * ICR is internally a single 64-bit register, but needs to be
2903 * split to ICR+ICR2 in userspace for backwards compatibility.
2906 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2908 icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
2909 (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
2910 __kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
2912 icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
2913 __kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
2920 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2922 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2925 * Get calculated timer current count for remaining timer period (if
2926 * any) and store it in the returned register set.
2928 __kvm_lapic_set_reg(s->regs, APIC_TMCCT,
2929 __apic_read(vcpu->arch.apic, APIC_TMCCT));
2931 return kvm_apic_state_fixup(vcpu, s, false);
2934 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2936 struct kvm_lapic *apic = vcpu->arch.apic;
2939 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2940 /* set SPIV separately to get count of SW disabled APICs right */
2941 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2943 r = kvm_apic_state_fixup(vcpu, s, true);
2945 kvm_recalculate_apic_map(vcpu->kvm);
2948 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2950 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2951 kvm_recalculate_apic_map(vcpu->kvm);
2952 kvm_apic_set_version(vcpu);
2954 apic_update_ppr(apic);
2955 cancel_apic_timer(apic);
2956 apic->lapic_timer.expired_tscdeadline = 0;
2957 apic_update_lvtt(apic);
2958 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2959 update_divide_count(apic);
2960 __start_apic_timer(apic, APIC_TMCCT);
2961 kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
2962 kvm_apic_update_apicv(vcpu);
2963 if (apic->apicv_active) {
2964 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2965 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
2966 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
2968 kvm_make_request(KVM_REQ_EVENT, vcpu);
2969 if (ioapic_in_kernel(vcpu->kvm))
2970 kvm_rtc_eoi_tracking_restore_one(vcpu);
2972 vcpu->arch.apic_arb_prio = 0;
2977 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2979 struct hrtimer *timer;
2981 if (!lapic_in_kernel(vcpu) ||
2982 kvm_can_post_timer_interrupt(vcpu))
2985 timer = &vcpu->arch.apic->lapic_timer.timer;
2986 if (hrtimer_cancel(timer))
2987 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2991 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2993 * Detect whether guest triggered PV EOI since the
2994 * last entry. If yes, set EOI on guests's behalf.
2995 * Clear PV EOI in guest memory in any case.
2997 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2998 struct kvm_lapic *apic)
3002 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
3003 * and KVM_PV_EOI_ENABLED in guest memory as follows:
3005 * KVM_APIC_PV_EOI_PENDING is unset:
3006 * -> host disabled PV EOI.
3007 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
3008 * -> host enabled PV EOI, guest did not execute EOI yet.
3009 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
3010 * -> host enabled PV EOI, guest executed EOI.
3012 BUG_ON(!pv_eoi_enabled(vcpu));
3014 if (pv_eoi_test_and_clr_pending(vcpu))
3016 vector = apic_set_eoi(apic);
3017 trace_kvm_pv_eoi(apic, vector);
3020 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3024 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
3025 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
3027 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3030 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3034 apic_set_tpr(vcpu->arch.apic, data & 0xff);
3038 * apic_sync_pv_eoi_to_guest - called before vmentry
3040 * Detect whether it's safe to enable PV EOI and
3043 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
3044 struct kvm_lapic *apic)
3046 if (!pv_eoi_enabled(vcpu) ||
3047 /* IRR set or many bits in ISR: could be nested. */
3048 apic->irr_pending ||
3049 /* Cache not set: could be safe but we don't bother. */
3050 apic->highest_isr_cache == -1 ||
3051 /* Need EOI to update ioapic. */
3052 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
3054 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
3055 * so we need not do anything here.
3060 pv_eoi_set_pending(apic->vcpu);
3063 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3066 int max_irr, max_isr;
3067 struct kvm_lapic *apic = vcpu->arch.apic;
3069 apic_sync_pv_eoi_to_guest(vcpu, apic);
3071 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
3074 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
3075 max_irr = apic_find_highest_irr(apic);
3078 max_isr = apic_find_highest_isr(apic);
3081 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
3083 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3087 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
3090 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
3091 &vcpu->arch.apic->vapic_cache,
3092 vapic_addr, sizeof(u32)))
3094 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3096 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
3099 vcpu->arch.apic->vapic_addr = vapic_addr;
3103 int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
3105 data &= ~APIC_ICR_BUSY;
3107 kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
3108 kvm_lapic_set_reg64(apic, APIC_ICR, data);
3109 trace_kvm_apic_write(APIC_ICR, data);
3113 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
3117 if (reg == APIC_ICR) {
3118 *data = kvm_lapic_get_reg64(apic, APIC_ICR);
3122 if (kvm_lapic_reg_read(apic, reg, 4, &low))
3130 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
3133 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
3134 * can be written as such, all other registers remain accessible only
3135 * through 32-bit reads/writes.
3137 if (reg == APIC_ICR)
3138 return kvm_x2apic_icr_write(apic, data);
3140 /* Bits 63:32 are reserved in all other registers. */
3144 return kvm_lapic_reg_write(apic, reg, (u32)data);
3147 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
3149 struct kvm_lapic *apic = vcpu->arch.apic;
3150 u32 reg = (msr - APIC_BASE_MSR) << 4;
3152 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3155 return kvm_lapic_msr_write(apic, reg, data);
3158 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
3160 struct kvm_lapic *apic = vcpu->arch.apic;
3161 u32 reg = (msr - APIC_BASE_MSR) << 4;
3163 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
3166 return kvm_lapic_msr_read(apic, reg, data);
3169 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
3171 if (!lapic_in_kernel(vcpu))
3174 return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
3177 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
3179 if (!lapic_in_kernel(vcpu))
3182 return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
3185 int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3187 u64 addr = data & ~KVM_MSR_ENABLED;
3188 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3189 unsigned long new_len;
3192 if (!IS_ALIGNED(addr, 4))
3195 if (data & KVM_MSR_ENABLED) {
3196 if (addr == ghc->gpa && len <= ghc->len)
3201 ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3206 vcpu->arch.pv_eoi.msr_val = data;
3211 int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
3213 struct kvm_lapic *apic = vcpu->arch.apic;
3217 if (!kvm_apic_has_pending_init_or_sipi(vcpu))
3220 if (is_guest_mode(vcpu)) {
3221 r = kvm_check_nested_events(vcpu);
3223 return r == -EBUSY ? 0 : r;
3225 * Continue processing INIT/SIPI even if a nested VM-Exit
3226 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
3227 * are blocked as a result of transitioning to VMX root mode.
3232 * INITs are blocked while CPU is in specific states (SMM, VMX root
3233 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
3234 * wait-for-SIPI (WFS).
3236 if (!kvm_apic_init_sipi_allowed(vcpu)) {
3237 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3238 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
3242 if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3243 kvm_vcpu_reset(vcpu, true);
3244 if (kvm_vcpu_is_bsp(apic->vcpu))
3245 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3247 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
3249 if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3250 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
3251 /* evaluate pending_events before reading the vector */
3253 sipi_vector = apic->sipi_vector;
3254 static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
3255 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3261 void kvm_lapic_exit(void)
3263 static_key_deferred_flush(&apic_hw_disabled);
3264 WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3265 static_key_deferred_flush(&apic_sw_disabled);
3266 WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));