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.
19 #include <linux/kvm_host.h>
20 #include <linux/kvm.h>
22 #include <linux/highmem.h>
23 #include <linux/smp.h>
24 #include <linux/hrtimer.h>
26 #include <linux/export.h>
27 #include <linux/math64.h>
28 #include <linux/slab.h>
29 #include <asm/processor.h>
33 #include <asm/current.h>
34 #include <asm/apicdef.h>
35 #include <asm/delay.h>
36 #include <linux/atomic.h>
37 #include <linux/jump_label.h>
38 #include "kvm_cache_regs.h"
48 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
50 #define mod_64(x, y) ((x) % (y))
58 /* 14 is the version for Xeon and Pentium 8.4.8*/
59 #define APIC_VERSION 0x14UL
60 #define LAPIC_MMIO_LENGTH (1 << 12)
61 /* followed define is not in apicdef.h */
62 #define MAX_APIC_VECTOR 256
63 #define APIC_VECTORS_PER_REG 32
65 static bool lapic_timer_advance_dynamic __read_mostly;
66 #define LAPIC_TIMER_ADVANCE_ADJUST_MIN 100 /* clock cycles */
67 #define LAPIC_TIMER_ADVANCE_ADJUST_MAX 10000 /* clock cycles */
68 #define LAPIC_TIMER_ADVANCE_NS_INIT 1000
69 #define LAPIC_TIMER_ADVANCE_NS_MAX 5000
70 /* step-by-step approximation to mitigate fluctuation */
71 #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
72 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data);
73 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
75 static inline void __kvm_lapic_set_reg(char *regs, int reg_off, u32 val)
77 *((u32 *) (regs + reg_off)) = val;
80 static inline void kvm_lapic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
82 __kvm_lapic_set_reg(apic->regs, reg_off, val);
85 static __always_inline u64 __kvm_lapic_get_reg64(char *regs, int reg)
87 BUILD_BUG_ON(reg != APIC_ICR);
88 return *((u64 *) (regs + reg));
91 static __always_inline u64 kvm_lapic_get_reg64(struct kvm_lapic *apic, int reg)
93 return __kvm_lapic_get_reg64(apic->regs, reg);
96 static __always_inline void __kvm_lapic_set_reg64(char *regs, int reg, u64 val)
98 BUILD_BUG_ON(reg != APIC_ICR);
99 *((u64 *) (regs + reg)) = val;
102 static __always_inline void kvm_lapic_set_reg64(struct kvm_lapic *apic,
105 __kvm_lapic_set_reg64(apic->regs, reg, val);
108 static inline int apic_test_vector(int vec, void *bitmap)
110 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
113 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
115 struct kvm_lapic *apic = vcpu->arch.apic;
117 return apic_test_vector(vector, apic->regs + APIC_ISR) ||
118 apic_test_vector(vector, apic->regs + APIC_IRR);
121 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
123 return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
126 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
128 return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
131 __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_hw_disabled, HZ);
132 __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_sw_disabled, HZ);
134 static inline int apic_enabled(struct kvm_lapic *apic)
136 return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
140 (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
143 (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
144 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
146 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
148 return apic->vcpu->vcpu_id;
151 static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
153 return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
154 (kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
157 bool kvm_can_use_hv_timer(struct kvm_vcpu *vcpu)
159 return kvm_x86_ops.set_hv_timer
160 && !(kvm_mwait_in_guest(vcpu->kvm) ||
161 kvm_can_post_timer_interrupt(vcpu));
163 EXPORT_SYMBOL_GPL(kvm_can_use_hv_timer);
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 bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
171 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
173 case KVM_APIC_MODE_X2APIC: {
174 u32 offset = (dest_id >> 16) * 16;
175 u32 max_apic_id = map->max_apic_id;
177 if (offset <= max_apic_id) {
178 u8 cluster_size = min(max_apic_id - offset + 1, 16U);
180 offset = array_index_nospec(offset, map->max_apic_id + 1);
181 *cluster = &map->phys_map[offset];
182 *mask = dest_id & (0xffff >> (16 - cluster_size));
189 case KVM_APIC_MODE_XAPIC_FLAT:
190 *cluster = map->xapic_flat_map;
191 *mask = dest_id & 0xff;
193 case KVM_APIC_MODE_XAPIC_CLUSTER:
194 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
195 *mask = dest_id & 0xf;
203 static void kvm_apic_map_free(struct rcu_head *rcu)
205 struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
211 * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
213 * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
214 * apic_map_lock_held.
222 void kvm_recalculate_apic_map(struct kvm *kvm)
224 struct kvm_apic_map *new, *old = NULL;
225 struct kvm_vcpu *vcpu;
227 u32 max_id = 255; /* enough space for any xAPIC ID */
229 /* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map. */
230 if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
233 WARN_ONCE(!irqchip_in_kernel(kvm),
234 "Dirty APIC map without an in-kernel local APIC");
236 mutex_lock(&kvm->arch.apic_map_lock);
238 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map
239 * (if clean) or the APIC registers (if dirty).
241 if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
242 DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
243 /* Someone else has updated the map. */
244 mutex_unlock(&kvm->arch.apic_map_lock);
248 kvm_for_each_vcpu(i, vcpu, kvm)
249 if (kvm_apic_present(vcpu))
250 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
252 new = kvzalloc(sizeof(struct kvm_apic_map) +
253 sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
259 new->max_apic_id = max_id;
261 kvm_for_each_vcpu(i, vcpu, kvm) {
262 struct kvm_lapic *apic = vcpu->arch.apic;
263 struct kvm_lapic **cluster;
269 if (!kvm_apic_present(vcpu))
272 xapic_id = kvm_xapic_id(apic);
273 x2apic_id = kvm_x2apic_id(apic);
275 /* Hotplug hack: see kvm_apic_match_physical_addr(), ... */
276 if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
277 x2apic_id <= new->max_apic_id)
278 new->phys_map[x2apic_id] = apic;
280 * ... xAPIC ID of VCPUs with APIC ID > 0xff will wrap-around,
281 * prevent them from masking VCPUs with APIC ID <= 0xff.
283 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
284 new->phys_map[xapic_id] = apic;
286 if (!kvm_apic_sw_enabled(apic))
289 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
291 if (apic_x2apic_mode(apic)) {
292 new->mode |= KVM_APIC_MODE_X2APIC;
294 ldr = GET_APIC_LOGICAL_ID(ldr);
295 if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
296 new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
298 new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
301 if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
305 cluster[ffs(mask) - 1] = apic;
308 old = rcu_dereference_protected(kvm->arch.apic_map,
309 lockdep_is_held(&kvm->arch.apic_map_lock));
310 rcu_assign_pointer(kvm->arch.apic_map, new);
312 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
313 * If another update has come in, leave it DIRTY.
315 atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
316 UPDATE_IN_PROGRESS, CLEAN);
317 mutex_unlock(&kvm->arch.apic_map_lock);
320 call_rcu(&old->rcu, kvm_apic_map_free);
322 kvm_make_scan_ioapic_request(kvm);
325 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
327 bool enabled = val & APIC_SPIV_APIC_ENABLED;
329 kvm_lapic_set_reg(apic, APIC_SPIV, val);
331 if (enabled != apic->sw_enabled) {
332 apic->sw_enabled = enabled;
334 static_branch_slow_dec_deferred(&apic_sw_disabled);
336 static_branch_inc(&apic_sw_disabled.key);
338 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
341 /* Check if there are APF page ready requests pending */
343 kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
344 kvm_xen_sw_enable_lapic(apic->vcpu);
348 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
350 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
351 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
354 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
356 kvm_lapic_set_reg(apic, APIC_LDR, id);
357 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
360 static inline void kvm_apic_set_dfr(struct kvm_lapic *apic, u32 val)
362 kvm_lapic_set_reg(apic, APIC_DFR, val);
363 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
366 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
368 return ((id >> 4) << 16) | (1 << (id & 0xf));
371 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
373 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
375 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
377 kvm_lapic_set_reg(apic, APIC_ID, id);
378 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
379 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
382 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
384 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
387 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
389 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
392 static inline int apic_lvtt_period(struct kvm_lapic *apic)
394 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
397 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
399 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
402 static inline int apic_lvt_nmi_mode(u32 lvt_val)
404 return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
407 static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
409 return apic->nr_lvt_entries > lvt_index;
412 static inline int kvm_apic_calc_nr_lvt_entries(struct kvm_vcpu *vcpu)
414 return KVM_APIC_MAX_NR_LVT_ENTRIES - !(vcpu->arch.mcg_cap & MCG_CMCI_P);
417 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
419 struct kvm_lapic *apic = vcpu->arch.apic;
422 if (!lapic_in_kernel(vcpu))
425 v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
428 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
429 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
430 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
431 * version first and level-triggered interrupts never get EOIed in
434 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC) &&
435 !ioapic_in_kernel(vcpu->kvm))
436 v |= APIC_LVR_DIRECTED_EOI;
437 kvm_lapic_set_reg(apic, APIC_LVR, v);
440 void kvm_apic_after_set_mcg_cap(struct kvm_vcpu *vcpu)
442 int nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
443 struct kvm_lapic *apic = vcpu->arch.apic;
446 if (!lapic_in_kernel(vcpu) || nr_lvt_entries == apic->nr_lvt_entries)
449 /* Initialize/mask any "new" LVT entries. */
450 for (i = apic->nr_lvt_entries; i < nr_lvt_entries; i++)
451 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
453 apic->nr_lvt_entries = nr_lvt_entries;
455 /* The number of LVT entries is reflected in the version register. */
456 kvm_apic_set_version(vcpu);
459 static const unsigned int apic_lvt_mask[KVM_APIC_MAX_NR_LVT_ENTRIES] = {
460 [LVT_TIMER] = LVT_MASK, /* timer mode mask added at runtime */
461 [LVT_THERMAL_MONITOR] = LVT_MASK | APIC_MODE_MASK,
462 [LVT_PERFORMANCE_COUNTER] = LVT_MASK | APIC_MODE_MASK,
463 [LVT_LINT0] = LINT_MASK,
464 [LVT_LINT1] = LINT_MASK,
465 [LVT_ERROR] = LVT_MASK,
466 [LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
469 static int find_highest_vector(void *bitmap)
474 for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
475 vec >= 0; vec -= APIC_VECTORS_PER_REG) {
476 reg = bitmap + REG_POS(vec);
478 return __fls(*reg) + vec;
484 static u8 count_vectors(void *bitmap)
490 for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
491 reg = bitmap + REG_POS(vec);
492 count += hweight32(*reg);
498 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
501 u32 pir_val, irr_val, prev_irr_val;
504 max_updated_irr = -1;
507 for (i = vec = 0; i <= 7; i++, vec += 32) {
508 pir_val = READ_ONCE(pir[i]);
509 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
511 prev_irr_val = irr_val;
512 irr_val |= xchg(&pir[i], 0);
513 *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
514 if (prev_irr_val != irr_val) {
516 __fls(irr_val ^ prev_irr_val) + vec;
520 *max_irr = __fls(irr_val) + vec;
523 return ((max_updated_irr != -1) &&
524 (max_updated_irr == *max_irr));
526 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
528 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
530 struct kvm_lapic *apic = vcpu->arch.apic;
532 return __kvm_apic_update_irr(pir, apic->regs, max_irr);
534 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
536 static inline int apic_search_irr(struct kvm_lapic *apic)
538 return find_highest_vector(apic->regs + APIC_IRR);
541 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
546 * Note that irr_pending is just a hint. It will be always
547 * true with virtual interrupt delivery enabled.
549 if (!apic->irr_pending)
552 result = apic_search_irr(apic);
553 ASSERT(result == -1 || result >= 16);
558 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
560 if (unlikely(apic->apicv_active)) {
561 /* need to update RVI */
562 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
563 static_call_cond(kvm_x86_hwapic_irr_update)(apic->vcpu,
564 apic_find_highest_irr(apic));
566 apic->irr_pending = false;
567 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
568 if (apic_search_irr(apic) != -1)
569 apic->irr_pending = true;
573 void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
575 apic_clear_irr(vec, vcpu->arch.apic);
577 EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
579 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
581 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
585 * With APIC virtualization enabled, all caching is disabled
586 * because the processor can modify ISR under the hood. Instead
589 if (unlikely(apic->apicv_active))
590 static_call_cond(kvm_x86_hwapic_isr_update)(vec);
593 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
595 * ISR (in service register) bit is set when injecting an interrupt.
596 * The highest vector is injected. Thus the latest bit set matches
597 * the highest bit in ISR.
599 apic->highest_isr_cache = vec;
603 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
608 * Note that isr_count is always 1, and highest_isr_cache
609 * is always -1, with APIC virtualization enabled.
611 if (!apic->isr_count)
613 if (likely(apic->highest_isr_cache != -1))
614 return apic->highest_isr_cache;
616 result = find_highest_vector(apic->regs + APIC_ISR);
617 ASSERT(result == -1 || result >= 16);
622 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
624 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
628 * We do get here for APIC virtualization enabled if the guest
629 * uses the Hyper-V APIC enlightenment. In this case we may need
630 * to trigger a new interrupt delivery by writing the SVI field;
631 * on the other hand isr_count and highest_isr_cache are unused
632 * and must be left alone.
634 if (unlikely(apic->apicv_active))
635 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
638 BUG_ON(apic->isr_count < 0);
639 apic->highest_isr_cache = -1;
643 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
645 /* This may race with setting of irr in __apic_accept_irq() and
646 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
647 * will cause vmexit immediately and the value will be recalculated
648 * on the next vmentry.
650 return apic_find_highest_irr(vcpu->arch.apic);
652 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
654 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
655 int vector, int level, int trig_mode,
656 struct dest_map *dest_map);
658 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
659 struct dest_map *dest_map)
661 struct kvm_lapic *apic = vcpu->arch.apic;
663 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
664 irq->level, irq->trig_mode, dest_map);
667 static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
668 struct kvm_lapic_irq *irq, u32 min)
671 struct kvm_vcpu *vcpu;
673 if (min > map->max_apic_id)
676 for_each_set_bit(i, ipi_bitmap,
677 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
678 if (map->phys_map[min + i]) {
679 vcpu = map->phys_map[min + i]->vcpu;
680 count += kvm_apic_set_irq(vcpu, irq, NULL);
687 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
688 unsigned long ipi_bitmap_high, u32 min,
689 unsigned long icr, int op_64_bit)
691 struct kvm_apic_map *map;
692 struct kvm_lapic_irq irq = {0};
693 int cluster_size = op_64_bit ? 64 : 32;
696 if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
699 irq.vector = icr & APIC_VECTOR_MASK;
700 irq.delivery_mode = icr & APIC_MODE_MASK;
701 irq.level = (icr & APIC_INT_ASSERT) != 0;
702 irq.trig_mode = icr & APIC_INT_LEVELTRIG;
705 map = rcu_dereference(kvm->arch.apic_map);
709 count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
711 count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
718 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
721 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
725 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
728 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
732 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
734 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
737 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
739 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
742 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
745 static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
749 if (pv_eoi_get_user(vcpu, &val) < 0)
752 val &= KVM_PV_EOI_ENABLED;
754 if (val && pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0)
758 * Clear pending bit in any case: it will be set again on vmentry.
759 * While this might not be ideal from performance point of view,
760 * this makes sure pv eoi is only enabled when we know it's safe.
762 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
767 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
770 if (kvm_x86_ops.sync_pir_to_irr)
771 highest_irr = static_call(kvm_x86_sync_pir_to_irr)(apic->vcpu);
773 highest_irr = apic_find_highest_irr(apic);
774 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
779 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
781 u32 tpr, isrv, ppr, old_ppr;
784 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
785 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
786 isr = apic_find_highest_isr(apic);
787 isrv = (isr != -1) ? isr : 0;
789 if ((tpr & 0xf0) >= (isrv & 0xf0))
796 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
798 return ppr < old_ppr;
801 static void apic_update_ppr(struct kvm_lapic *apic)
805 if (__apic_update_ppr(apic, &ppr) &&
806 apic_has_interrupt_for_ppr(apic, ppr) != -1)
807 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
810 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
812 apic_update_ppr(vcpu->arch.apic);
814 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
816 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
818 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
819 apic_update_ppr(apic);
822 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
824 return mda == (apic_x2apic_mode(apic) ?
825 X2APIC_BROADCAST : APIC_BROADCAST);
828 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
830 if (kvm_apic_broadcast(apic, mda))
834 * Hotplug hack: Accept interrupts for vCPUs in xAPIC mode as if they
835 * were in x2APIC mode if the target APIC ID can't be encoded as an
836 * xAPIC ID. This allows unique addressing of hotplugged vCPUs (which
837 * start in xAPIC mode) with an APIC ID that is unaddressable in xAPIC
838 * mode. Match the x2APIC ID if and only if the target APIC ID can't
839 * be encoded in xAPIC to avoid spurious matches against a vCPU that
840 * changed its (addressable) xAPIC ID (which is writable).
842 if (apic_x2apic_mode(apic) || mda > 0xff)
843 return mda == kvm_x2apic_id(apic);
845 return mda == kvm_xapic_id(apic);
848 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
852 if (kvm_apic_broadcast(apic, mda))
855 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
857 if (apic_x2apic_mode(apic))
858 return ((logical_id >> 16) == (mda >> 16))
859 && (logical_id & mda & 0xffff) != 0;
861 logical_id = GET_APIC_LOGICAL_ID(logical_id);
863 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
865 return (logical_id & mda) != 0;
866 case APIC_DFR_CLUSTER:
867 return ((logical_id >> 4) == (mda >> 4))
868 && (logical_id & mda & 0xf) != 0;
874 /* The KVM local APIC implementation has two quirks:
876 * - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
877 * in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
878 * KVM doesn't do that aliasing.
880 * - in-kernel IOAPIC messages have to be delivered directly to
881 * x2APIC, because the kernel does not support interrupt remapping.
882 * In order to support broadcast without interrupt remapping, x2APIC
883 * rewrites the destination of non-IPI messages from APIC_BROADCAST
884 * to X2APIC_BROADCAST.
886 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API. This is
887 * important when userspace wants to use x2APIC-format MSIs, because
888 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
890 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
891 struct kvm_lapic *source, struct kvm_lapic *target)
893 bool ipi = source != NULL;
895 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
896 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
897 return X2APIC_BROADCAST;
902 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
903 int shorthand, unsigned int dest, int dest_mode)
905 struct kvm_lapic *target = vcpu->arch.apic;
906 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
910 case APIC_DEST_NOSHORT:
911 if (dest_mode == APIC_DEST_PHYSICAL)
912 return kvm_apic_match_physical_addr(target, mda);
914 return kvm_apic_match_logical_addr(target, mda);
916 return target == source;
917 case APIC_DEST_ALLINC:
919 case APIC_DEST_ALLBUT:
920 return target != source;
925 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
927 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
928 const unsigned long *bitmap, u32 bitmap_size)
933 mod = vector % dest_vcpus;
935 for (i = 0; i <= mod; i++) {
936 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
937 BUG_ON(idx == bitmap_size);
943 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
945 if (!kvm->arch.disabled_lapic_found) {
946 kvm->arch.disabled_lapic_found = true;
948 "Disabled LAPIC found during irq injection\n");
952 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
953 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
955 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
956 if ((irq->dest_id == APIC_BROADCAST &&
957 map->mode != KVM_APIC_MODE_X2APIC))
959 if (irq->dest_id == X2APIC_BROADCAST)
962 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
963 if (irq->dest_id == (x2apic_ipi ?
964 X2APIC_BROADCAST : APIC_BROADCAST))
971 /* Return true if the interrupt can be handled by using *bitmap as index mask
972 * for valid destinations in *dst array.
973 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
974 * Note: we may have zero kvm_lapic destinations when we return true, which
975 * means that the interrupt should be dropped. In this case, *bitmap would be
976 * zero and *dst undefined.
978 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
979 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
980 struct kvm_apic_map *map, struct kvm_lapic ***dst,
981 unsigned long *bitmap)
985 if (irq->shorthand == APIC_DEST_SELF && src) {
989 } else if (irq->shorthand)
992 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
995 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
996 if (irq->dest_id > map->max_apic_id) {
999 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
1000 *dst = &map->phys_map[dest_id];
1007 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1011 if (!kvm_lowest_prio_delivery(irq))
1014 if (!kvm_vector_hashing_enabled()) {
1016 for_each_set_bit(i, bitmap, 16) {
1021 else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
1022 (*dst)[lowest]->vcpu) < 0)
1029 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
1032 if (!(*dst)[lowest]) {
1033 kvm_apic_disabled_lapic_found(kvm);
1039 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
1044 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
1045 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
1047 struct kvm_apic_map *map;
1048 unsigned long bitmap;
1049 struct kvm_lapic **dst = NULL;
1055 if (irq->shorthand == APIC_DEST_SELF) {
1056 if (KVM_BUG_ON(!src, kvm)) {
1060 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
1065 map = rcu_dereference(kvm->arch.apic_map);
1067 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
1070 for_each_set_bit(i, &bitmap, 16) {
1073 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
1082 * This routine tries to handle interrupts in posted mode, here is how
1083 * it deals with different cases:
1084 * - For single-destination interrupts, handle it in posted mode
1085 * - Else if vector hashing is enabled and it is a lowest-priority
1086 * interrupt, handle it in posted mode and use the following mechanism
1087 * to find the destination vCPU.
1088 * 1. For lowest-priority interrupts, store all the possible
1089 * destination vCPUs in an array.
1090 * 2. Use "guest vector % max number of destination vCPUs" to find
1091 * the right destination vCPU in the array for the lowest-priority
1093 * - Otherwise, use remapped mode to inject the interrupt.
1095 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
1096 struct kvm_vcpu **dest_vcpu)
1098 struct kvm_apic_map *map;
1099 unsigned long bitmap;
1100 struct kvm_lapic **dst = NULL;
1107 map = rcu_dereference(kvm->arch.apic_map);
1109 if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1110 hweight16(bitmap) == 1) {
1111 unsigned long i = find_first_bit(&bitmap, 16);
1114 *dest_vcpu = dst[i]->vcpu;
1124 * Add a pending IRQ into lapic.
1125 * Return 1 if successfully added and 0 if discarded.
1127 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1128 int vector, int level, int trig_mode,
1129 struct dest_map *dest_map)
1132 struct kvm_vcpu *vcpu = apic->vcpu;
1134 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1136 switch (delivery_mode) {
1137 case APIC_DM_LOWEST:
1138 vcpu->arch.apic_arb_prio++;
1141 if (unlikely(trig_mode && !level))
1144 /* FIXME add logic for vcpu on reset */
1145 if (unlikely(!apic_enabled(apic)))
1151 __set_bit(vcpu->vcpu_id, dest_map->map);
1152 dest_map->vectors[vcpu->vcpu_id] = vector;
1155 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1157 kvm_lapic_set_vector(vector,
1158 apic->regs + APIC_TMR);
1160 kvm_lapic_clear_vector(vector,
1161 apic->regs + APIC_TMR);
1164 static_call(kvm_x86_deliver_interrupt)(apic, delivery_mode,
1170 vcpu->arch.pv.pv_unhalted = 1;
1171 kvm_make_request(KVM_REQ_EVENT, vcpu);
1172 kvm_vcpu_kick(vcpu);
1177 kvm_make_request(KVM_REQ_SMI, vcpu);
1178 kvm_vcpu_kick(vcpu);
1183 kvm_inject_nmi(vcpu);
1184 kvm_vcpu_kick(vcpu);
1188 if (!trig_mode || level) {
1190 /* assumes that there are only KVM_APIC_INIT/SIPI */
1191 apic->pending_events = (1UL << KVM_APIC_INIT);
1192 kvm_make_request(KVM_REQ_EVENT, vcpu);
1193 kvm_vcpu_kick(vcpu);
1197 case APIC_DM_STARTUP:
1199 apic->sipi_vector = vector;
1200 /* make sure sipi_vector is visible for the receiver */
1202 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1203 kvm_make_request(KVM_REQ_EVENT, vcpu);
1204 kvm_vcpu_kick(vcpu);
1207 case APIC_DM_EXTINT:
1209 * Should only be called by kvm_apic_local_deliver() with LVT0,
1210 * before NMI watchdog was enabled. Already handled by
1211 * kvm_apic_accept_pic_intr().
1216 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1224 * This routine identifies the destination vcpus mask meant to receive the
1225 * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
1226 * out the destination vcpus array and set the bitmap or it traverses to
1227 * each available vcpu to identify the same.
1229 void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
1230 unsigned long *vcpu_bitmap)
1232 struct kvm_lapic **dest_vcpu = NULL;
1233 struct kvm_lapic *src = NULL;
1234 struct kvm_apic_map *map;
1235 struct kvm_vcpu *vcpu;
1236 unsigned long bitmap, i;
1241 map = rcu_dereference(kvm->arch.apic_map);
1243 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
1246 for_each_set_bit(i, &bitmap, 16) {
1249 vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
1250 __set_bit(vcpu_idx, vcpu_bitmap);
1253 kvm_for_each_vcpu(i, vcpu, kvm) {
1254 if (!kvm_apic_present(vcpu))
1256 if (!kvm_apic_match_dest(vcpu, NULL,
1261 __set_bit(i, vcpu_bitmap);
1267 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1269 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1272 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1274 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1277 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1281 /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1282 if (!kvm_ioapic_handles_vector(apic, vector))
1285 /* Request a KVM exit to inform the userspace IOAPIC. */
1286 if (irqchip_split(apic->vcpu->kvm)) {
1287 apic->vcpu->arch.pending_ioapic_eoi = vector;
1288 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1292 if (apic_test_vector(vector, apic->regs + APIC_TMR))
1293 trigger_mode = IOAPIC_LEVEL_TRIG;
1295 trigger_mode = IOAPIC_EDGE_TRIG;
1297 kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1300 static int apic_set_eoi(struct kvm_lapic *apic)
1302 int vector = apic_find_highest_isr(apic);
1304 trace_kvm_eoi(apic, vector);
1307 * Not every write EOI will has corresponding ISR,
1308 * one example is when Kernel check timer on setup_IO_APIC
1313 apic_clear_isr(vector, apic);
1314 apic_update_ppr(apic);
1316 if (to_hv_vcpu(apic->vcpu) &&
1317 test_bit(vector, to_hv_synic(apic->vcpu)->vec_bitmap))
1318 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1320 kvm_ioapic_send_eoi(apic, vector);
1321 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1326 * this interface assumes a trap-like exit, which has already finished
1327 * desired side effect including vISR and vPPR update.
1329 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1331 struct kvm_lapic *apic = vcpu->arch.apic;
1333 trace_kvm_eoi(apic, vector);
1335 kvm_ioapic_send_eoi(apic, vector);
1336 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1338 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1340 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1342 struct kvm_lapic_irq irq;
1344 /* KVM has no delay and should always clear the BUSY/PENDING flag. */
1345 WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1347 irq.vector = icr_low & APIC_VECTOR_MASK;
1348 irq.delivery_mode = icr_low & APIC_MODE_MASK;
1349 irq.dest_mode = icr_low & APIC_DEST_MASK;
1350 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1351 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1352 irq.shorthand = icr_low & APIC_SHORT_MASK;
1353 irq.msi_redir_hint = false;
1354 if (apic_x2apic_mode(apic))
1355 irq.dest_id = icr_high;
1357 irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
1359 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1361 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1363 EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1365 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1367 ktime_t remaining, now;
1371 ASSERT(apic != NULL);
1373 /* if initial count is 0, current count should also be 0 */
1374 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1375 apic->lapic_timer.period == 0)
1379 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1380 if (ktime_to_ns(remaining) < 0)
1383 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1384 tmcct = div64_u64(ns,
1385 (APIC_BUS_CYCLE_NS * apic->divide_count));
1390 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1392 struct kvm_vcpu *vcpu = apic->vcpu;
1393 struct kvm_run *run = vcpu->run;
1395 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1396 run->tpr_access.rip = kvm_rip_read(vcpu);
1397 run->tpr_access.is_write = write;
1400 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1402 if (apic->vcpu->arch.tpr_access_reporting)
1403 __report_tpr_access(apic, write);
1406 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1410 if (offset >= LAPIC_MMIO_LENGTH)
1417 case APIC_TMCCT: /* Timer CCR */
1418 if (apic_lvtt_tscdeadline(apic))
1421 val = apic_get_tmcct(apic);
1424 apic_update_ppr(apic);
1425 val = kvm_lapic_get_reg(apic, offset);
1428 report_tpr_access(apic, false);
1431 val = kvm_lapic_get_reg(apic, offset);
1438 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1440 return container_of(dev, struct kvm_lapic, dev);
1443 #define APIC_REG_MASK(reg) (1ull << ((reg) >> 4))
1444 #define APIC_REGS_MASK(first, count) \
1445 (APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1447 static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1450 unsigned char alignment = offset & 0xf;
1452 /* this bitmask has a bit cleared for each reserved register */
1453 u64 valid_reg_mask =
1454 APIC_REG_MASK(APIC_ID) |
1455 APIC_REG_MASK(APIC_LVR) |
1456 APIC_REG_MASK(APIC_TASKPRI) |
1457 APIC_REG_MASK(APIC_PROCPRI) |
1458 APIC_REG_MASK(APIC_LDR) |
1459 APIC_REG_MASK(APIC_DFR) |
1460 APIC_REG_MASK(APIC_SPIV) |
1461 APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1462 APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1463 APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1464 APIC_REG_MASK(APIC_ESR) |
1465 APIC_REG_MASK(APIC_ICR) |
1466 APIC_REG_MASK(APIC_LVTT) |
1467 APIC_REG_MASK(APIC_LVTTHMR) |
1468 APIC_REG_MASK(APIC_LVTPC) |
1469 APIC_REG_MASK(APIC_LVT0) |
1470 APIC_REG_MASK(APIC_LVT1) |
1471 APIC_REG_MASK(APIC_LVTERR) |
1472 APIC_REG_MASK(APIC_TMICT) |
1473 APIC_REG_MASK(APIC_TMCCT) |
1474 APIC_REG_MASK(APIC_TDCR);
1476 if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
1477 valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
1480 * ARBPRI and ICR2 are not valid in x2APIC mode. WARN if KVM reads ICR
1481 * in x2APIC mode as it's an 8-byte register in x2APIC and needs to be
1482 * manually handled by the caller.
1484 if (!apic_x2apic_mode(apic))
1485 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1486 APIC_REG_MASK(APIC_ICR2);
1488 WARN_ON_ONCE(offset == APIC_ICR);
1490 if (alignment + len > 4)
1493 if (offset > 0x3f0 || !(valid_reg_mask & APIC_REG_MASK(offset)))
1496 result = __apic_read(apic, offset & ~0xf);
1498 trace_kvm_apic_read(offset, result);
1504 memcpy(data, (char *)&result + alignment, len);
1507 printk(KERN_ERR "Local APIC read with len = %x, "
1508 "should be 1,2, or 4 instead\n", len);
1514 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1516 return addr >= apic->base_address &&
1517 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1520 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1521 gpa_t address, int len, void *data)
1523 struct kvm_lapic *apic = to_lapic(this);
1524 u32 offset = address - apic->base_address;
1526 if (!apic_mmio_in_range(apic, address))
1529 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1530 if (!kvm_check_has_quirk(vcpu->kvm,
1531 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1534 memset(data, 0xff, len);
1538 kvm_lapic_reg_read(apic, offset, len, data);
1543 static void update_divide_count(struct kvm_lapic *apic)
1545 u32 tmp1, tmp2, tdcr;
1547 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1549 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1550 apic->divide_count = 0x1 << (tmp2 & 0x7);
1553 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1556 * Do not allow the guest to program periodic timers with small
1557 * interval, since the hrtimers are not throttled by the host
1560 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1561 s64 min_period = min_timer_period_us * 1000LL;
1563 if (apic->lapic_timer.period < min_period) {
1564 pr_info_ratelimited(
1565 "kvm: vcpu %i: requested %lld ns "
1566 "lapic timer period limited to %lld ns\n",
1567 apic->vcpu->vcpu_id,
1568 apic->lapic_timer.period, min_period);
1569 apic->lapic_timer.period = min_period;
1574 static void cancel_hv_timer(struct kvm_lapic *apic);
1576 static void cancel_apic_timer(struct kvm_lapic *apic)
1578 hrtimer_cancel(&apic->lapic_timer.timer);
1580 if (apic->lapic_timer.hv_timer_in_use)
1581 cancel_hv_timer(apic);
1583 atomic_set(&apic->lapic_timer.pending, 0);
1586 static void apic_update_lvtt(struct kvm_lapic *apic)
1588 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1589 apic->lapic_timer.timer_mode_mask;
1591 if (apic->lapic_timer.timer_mode != timer_mode) {
1592 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1593 APIC_LVT_TIMER_TSCDEADLINE)) {
1594 cancel_apic_timer(apic);
1595 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1596 apic->lapic_timer.period = 0;
1597 apic->lapic_timer.tscdeadline = 0;
1599 apic->lapic_timer.timer_mode = timer_mode;
1600 limit_periodic_timer_frequency(apic);
1605 * On APICv, this test will cause a busy wait
1606 * during a higher-priority task.
1609 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1611 struct kvm_lapic *apic = vcpu->arch.apic;
1612 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1614 if (kvm_apic_hw_enabled(apic)) {
1615 int vec = reg & APIC_VECTOR_MASK;
1616 void *bitmap = apic->regs + APIC_ISR;
1618 if (apic->apicv_active)
1619 bitmap = apic->regs + APIC_IRR;
1621 if (apic_test_vector(vec, bitmap))
1627 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1629 u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1632 * If the guest TSC is running at a different ratio than the host, then
1633 * convert the delay to nanoseconds to achieve an accurate delay. Note
1634 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1635 * always for VMX enabled hardware.
1637 if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
1638 __delay(min(guest_cycles,
1639 nsec_to_cycles(vcpu, timer_advance_ns)));
1641 u64 delay_ns = guest_cycles * 1000000ULL;
1642 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1643 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1647 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1648 s64 advance_expire_delta)
1650 struct kvm_lapic *apic = vcpu->arch.apic;
1651 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1654 /* Do not adjust for tiny fluctuations or large random spikes. */
1655 if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1656 abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1660 if (advance_expire_delta < 0) {
1661 ns = -advance_expire_delta * 1000000ULL;
1662 do_div(ns, vcpu->arch.virtual_tsc_khz);
1663 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1666 ns = advance_expire_delta * 1000000ULL;
1667 do_div(ns, vcpu->arch.virtual_tsc_khz);
1668 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1671 if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1672 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1673 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1676 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1678 struct kvm_lapic *apic = vcpu->arch.apic;
1679 u64 guest_tsc, tsc_deadline;
1681 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1682 apic->lapic_timer.expired_tscdeadline = 0;
1683 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1684 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1686 if (lapic_timer_advance_dynamic) {
1687 adjust_lapic_timer_advance(vcpu, guest_tsc - tsc_deadline);
1689 * If the timer fired early, reread the TSC to account for the
1690 * overhead of the above adjustment to avoid waiting longer
1691 * than is necessary.
1693 if (guest_tsc < tsc_deadline)
1694 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1697 if (guest_tsc < tsc_deadline)
1698 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1701 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1703 if (lapic_in_kernel(vcpu) &&
1704 vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1705 vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1706 lapic_timer_int_injected(vcpu))
1707 __kvm_wait_lapic_expire(vcpu);
1709 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1711 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1713 struct kvm_timer *ktimer = &apic->lapic_timer;
1715 kvm_apic_local_deliver(apic, APIC_LVTT);
1716 if (apic_lvtt_tscdeadline(apic)) {
1717 ktimer->tscdeadline = 0;
1718 } else if (apic_lvtt_oneshot(apic)) {
1719 ktimer->tscdeadline = 0;
1720 ktimer->target_expiration = 0;
1724 static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
1726 struct kvm_vcpu *vcpu = apic->vcpu;
1727 struct kvm_timer *ktimer = &apic->lapic_timer;
1729 if (atomic_read(&apic->lapic_timer.pending))
1732 if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1733 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1735 if (!from_timer_fn && apic->apicv_active) {
1736 WARN_ON(kvm_get_running_vcpu() != vcpu);
1737 kvm_apic_inject_pending_timer_irqs(apic);
1741 if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1743 * Ensure the guest's timer has truly expired before posting an
1744 * interrupt. Open code the relevant checks to avoid querying
1745 * lapic_timer_int_injected(), which will be false since the
1746 * interrupt isn't yet injected. Waiting until after injecting
1747 * is not an option since that won't help a posted interrupt.
1749 if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1750 vcpu->arch.apic->lapic_timer.timer_advance_ns)
1751 __kvm_wait_lapic_expire(vcpu);
1752 kvm_apic_inject_pending_timer_irqs(apic);
1756 atomic_inc(&apic->lapic_timer.pending);
1757 kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1759 kvm_vcpu_kick(vcpu);
1762 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1764 struct kvm_timer *ktimer = &apic->lapic_timer;
1765 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1768 struct kvm_vcpu *vcpu = apic->vcpu;
1769 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1770 unsigned long flags;
1773 if (unlikely(!tscdeadline || !this_tsc_khz))
1776 local_irq_save(flags);
1779 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1781 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1782 do_div(ns, this_tsc_khz);
1784 if (likely(tscdeadline > guest_tsc) &&
1785 likely(ns > apic->lapic_timer.timer_advance_ns)) {
1786 expire = ktime_add_ns(now, ns);
1787 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1788 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1790 apic_timer_expired(apic, false);
1792 local_irq_restore(flags);
1795 static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1797 return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
1800 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1802 ktime_t now, remaining;
1803 u64 ns_remaining_old, ns_remaining_new;
1805 apic->lapic_timer.period =
1806 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1807 limit_periodic_timer_frequency(apic);
1810 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1811 if (ktime_to_ns(remaining) < 0)
1814 ns_remaining_old = ktime_to_ns(remaining);
1815 ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1816 apic->divide_count, old_divisor);
1818 apic->lapic_timer.tscdeadline +=
1819 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1820 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1821 apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1824 static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1831 apic->lapic_timer.period =
1832 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1834 if (!apic->lapic_timer.period) {
1835 apic->lapic_timer.tscdeadline = 0;
1839 limit_periodic_timer_frequency(apic);
1840 deadline = apic->lapic_timer.period;
1842 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1843 if (unlikely(count_reg != APIC_TMICT)) {
1844 deadline = tmict_to_ns(apic,
1845 kvm_lapic_get_reg(apic, count_reg));
1846 if (unlikely(deadline <= 0))
1847 deadline = apic->lapic_timer.period;
1848 else if (unlikely(deadline > apic->lapic_timer.period)) {
1849 pr_info_ratelimited(
1850 "kvm: vcpu %i: requested lapic timer restore with "
1851 "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
1852 "Using initial count to start timer.\n",
1853 apic->vcpu->vcpu_id,
1855 kvm_lapic_get_reg(apic, count_reg),
1856 deadline, apic->lapic_timer.period);
1857 kvm_lapic_set_reg(apic, count_reg, 0);
1858 deadline = apic->lapic_timer.period;
1863 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1864 nsec_to_cycles(apic->vcpu, deadline);
1865 apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
1870 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1872 ktime_t now = ktime_get();
1877 * Synchronize both deadlines to the same time source or
1878 * differences in the periods (caused by differences in the
1879 * underlying clocks or numerical approximation errors) will
1880 * cause the two to drift apart over time as the errors
1883 apic->lapic_timer.target_expiration =
1884 ktime_add_ns(apic->lapic_timer.target_expiration,
1885 apic->lapic_timer.period);
1886 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1887 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1888 nsec_to_cycles(apic->vcpu, delta);
1891 static void start_sw_period(struct kvm_lapic *apic)
1893 if (!apic->lapic_timer.period)
1896 if (ktime_after(ktime_get(),
1897 apic->lapic_timer.target_expiration)) {
1898 apic_timer_expired(apic, false);
1900 if (apic_lvtt_oneshot(apic))
1903 advance_periodic_target_expiration(apic);
1906 hrtimer_start(&apic->lapic_timer.timer,
1907 apic->lapic_timer.target_expiration,
1908 HRTIMER_MODE_ABS_HARD);
1911 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1913 if (!lapic_in_kernel(vcpu))
1916 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1918 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1920 static void cancel_hv_timer(struct kvm_lapic *apic)
1922 WARN_ON(preemptible());
1923 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1924 static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
1925 apic->lapic_timer.hv_timer_in_use = false;
1928 static bool start_hv_timer(struct kvm_lapic *apic)
1930 struct kvm_timer *ktimer = &apic->lapic_timer;
1931 struct kvm_vcpu *vcpu = apic->vcpu;
1934 WARN_ON(preemptible());
1935 if (!kvm_can_use_hv_timer(vcpu))
1938 if (!ktimer->tscdeadline)
1941 if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
1944 ktimer->hv_timer_in_use = true;
1945 hrtimer_cancel(&ktimer->timer);
1948 * To simplify handling the periodic timer, leave the hv timer running
1949 * even if the deadline timer has expired, i.e. rely on the resulting
1950 * VM-Exit to recompute the periodic timer's target expiration.
1952 if (!apic_lvtt_period(apic)) {
1954 * Cancel the hv timer if the sw timer fired while the hv timer
1955 * was being programmed, or if the hv timer itself expired.
1957 if (atomic_read(&ktimer->pending)) {
1958 cancel_hv_timer(apic);
1959 } else if (expired) {
1960 apic_timer_expired(apic, false);
1961 cancel_hv_timer(apic);
1965 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
1970 static void start_sw_timer(struct kvm_lapic *apic)
1972 struct kvm_timer *ktimer = &apic->lapic_timer;
1974 WARN_ON(preemptible());
1975 if (apic->lapic_timer.hv_timer_in_use)
1976 cancel_hv_timer(apic);
1977 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1980 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1981 start_sw_period(apic);
1982 else if (apic_lvtt_tscdeadline(apic))
1983 start_sw_tscdeadline(apic);
1984 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1987 static void restart_apic_timer(struct kvm_lapic *apic)
1991 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
1994 if (!start_hv_timer(apic))
1995 start_sw_timer(apic);
2000 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
2002 struct kvm_lapic *apic = vcpu->arch.apic;
2005 /* If the preempt notifier has already run, it also called apic_timer_expired */
2006 if (!apic->lapic_timer.hv_timer_in_use)
2008 WARN_ON(kvm_vcpu_is_blocking(vcpu));
2009 apic_timer_expired(apic, false);
2010 cancel_hv_timer(apic);
2012 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
2013 advance_periodic_target_expiration(apic);
2014 restart_apic_timer(apic);
2019 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
2021 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2023 restart_apic_timer(vcpu->arch.apic);
2026 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2028 struct kvm_lapic *apic = vcpu->arch.apic;
2031 /* Possibly the TSC deadline timer is not enabled yet */
2032 if (apic->lapic_timer.hv_timer_in_use)
2033 start_sw_timer(apic);
2037 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2039 struct kvm_lapic *apic = vcpu->arch.apic;
2041 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2042 restart_apic_timer(apic);
2045 static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2047 atomic_set(&apic->lapic_timer.pending, 0);
2049 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2050 && !set_target_expiration(apic, count_reg))
2053 restart_apic_timer(apic);
2056 static void start_apic_timer(struct kvm_lapic *apic)
2058 __start_apic_timer(apic, APIC_TMICT);
2061 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2063 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2065 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
2066 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
2067 if (lvt0_in_nmi_mode) {
2068 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2070 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2074 static void kvm_lapic_xapic_id_updated(struct kvm_lapic *apic)
2076 struct kvm *kvm = apic->vcpu->kvm;
2078 if (!kvm_apic_hw_enabled(apic))
2081 if (KVM_BUG_ON(apic_x2apic_mode(apic), kvm))
2085 * Deliberately truncate the vCPU ID when detecting a modified APIC ID
2086 * to avoid false positives if the vCPU ID, i.e. x2APIC ID, is a 32-bit
2089 if (kvm_xapic_id(apic) == (u8)apic->vcpu->vcpu_id)
2092 kvm_set_apicv_inhibit(apic->vcpu->kvm, APICV_INHIBIT_REASON_APIC_ID_MODIFIED);
2095 static int get_lvt_index(u32 reg)
2097 if (reg == APIC_LVTCMCI)
2099 if (reg < APIC_LVTT || reg > APIC_LVTERR)
2101 return array_index_nospec(
2102 (reg - APIC_LVTT) >> 4, KVM_APIC_MAX_NR_LVT_ENTRIES);
2105 static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2109 trace_kvm_apic_write(reg, val);
2112 case APIC_ID: /* Local APIC ID */
2113 if (!apic_x2apic_mode(apic)) {
2114 kvm_apic_set_xapic_id(apic, val >> 24);
2115 kvm_lapic_xapic_id_updated(apic);
2122 report_tpr_access(apic, true);
2123 apic_set_tpr(apic, val & 0xff);
2131 if (!apic_x2apic_mode(apic))
2132 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
2138 if (!apic_x2apic_mode(apic))
2139 kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2146 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2147 mask |= APIC_SPIV_DIRECTED_EOI;
2148 apic_set_spiv(apic, val & mask);
2149 if (!(val & APIC_SPIV_APIC_ENABLED)) {
2152 for (i = 0; i < apic->nr_lvt_entries; i++) {
2153 kvm_lapic_set_reg(apic, APIC_LVTx(i),
2154 kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
2156 apic_update_lvtt(apic);
2157 atomic_set(&apic->lapic_timer.pending, 0);
2163 WARN_ON_ONCE(apic_x2apic_mode(apic));
2165 /* No delay here, so we always clear the pending bit */
2166 val &= ~APIC_ICR_BUSY;
2167 kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2168 kvm_lapic_set_reg(apic, APIC_ICR, val);
2171 if (apic_x2apic_mode(apic))
2174 kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2178 apic_manage_nmi_watchdog(apic, val);
2184 case APIC_LVTCMCI: {
2185 u32 index = get_lvt_index(reg);
2186 if (!kvm_lapic_lvt_supported(apic, index)) {
2190 if (!kvm_apic_sw_enabled(apic))
2191 val |= APIC_LVT_MASKED;
2192 val &= apic_lvt_mask[index];
2193 kvm_lapic_set_reg(apic, reg, val);
2198 if (!kvm_apic_sw_enabled(apic))
2199 val |= APIC_LVT_MASKED;
2200 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
2201 kvm_lapic_set_reg(apic, APIC_LVTT, val);
2202 apic_update_lvtt(apic);
2206 if (apic_lvtt_tscdeadline(apic))
2209 cancel_apic_timer(apic);
2210 kvm_lapic_set_reg(apic, APIC_TMICT, val);
2211 start_apic_timer(apic);
2215 uint32_t old_divisor = apic->divide_count;
2217 kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2218 update_divide_count(apic);
2219 if (apic->divide_count != old_divisor &&
2220 apic->lapic_timer.period) {
2221 hrtimer_cancel(&apic->lapic_timer.timer);
2222 update_target_expiration(apic, old_divisor);
2223 restart_apic_timer(apic);
2228 if (apic_x2apic_mode(apic) && val != 0)
2234 * Self-IPI exists only when x2APIC is enabled. Bits 7:0 hold
2235 * the vector, everything else is reserved.
2237 if (!apic_x2apic_mode(apic) || (val & ~APIC_VECTOR_MASK))
2240 kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
2248 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2249 * was toggled, the APIC ID changed, etc... The maps are marked dirty
2250 * on relevant changes, i.e. this is a nop for most writes.
2252 kvm_recalculate_apic_map(apic->vcpu->kvm);
2257 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2258 gpa_t address, int len, const void *data)
2260 struct kvm_lapic *apic = to_lapic(this);
2261 unsigned int offset = address - apic->base_address;
2264 if (!apic_mmio_in_range(apic, address))
2267 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2268 if (!kvm_check_has_quirk(vcpu->kvm,
2269 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2276 * APIC register must be aligned on 128-bits boundary.
2277 * 32/64/128 bits registers must be accessed thru 32 bits.
2280 if (len != 4 || (offset & 0xf))
2285 kvm_lapic_reg_write(apic, offset & 0xff0, val);
2290 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2292 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2294 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2296 /* emulate APIC access in a trap manner */
2297 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2299 struct kvm_lapic *apic = vcpu->arch.apic;
2302 * ICR is a single 64-bit register when x2APIC is enabled, all others
2303 * registers hold 32-bit values. For legacy xAPIC, ICR writes need to
2304 * go down the common path to get the upper half from ICR2.
2306 * Note, using the write helpers may incur an unnecessary write to the
2307 * virtual APIC state, but KVM needs to conditionally modify the value
2308 * in certain cases, e.g. to clear the ICR busy bit. The cost of extra
2309 * conditional branches is likely a wash relative to the cost of the
2310 * maybe-unecessary write, and both are in the noise anyways.
2312 if (apic_x2apic_mode(apic) && offset == APIC_ICR)
2313 kvm_x2apic_icr_write(apic, kvm_lapic_get_reg64(apic, APIC_ICR));
2315 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
2317 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2319 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2321 struct kvm_lapic *apic = vcpu->arch.apic;
2323 if (!vcpu->arch.apic)
2326 hrtimer_cancel(&apic->lapic_timer.timer);
2328 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2329 static_branch_slow_dec_deferred(&apic_hw_disabled);
2331 if (!apic->sw_enabled)
2332 static_branch_slow_dec_deferred(&apic_sw_disabled);
2335 free_page((unsigned long)apic->regs);
2341 *----------------------------------------------------------------------
2343 *----------------------------------------------------------------------
2345 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2347 struct kvm_lapic *apic = vcpu->arch.apic;
2349 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2352 return apic->lapic_timer.tscdeadline;
2355 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2357 struct kvm_lapic *apic = vcpu->arch.apic;
2359 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2362 hrtimer_cancel(&apic->lapic_timer.timer);
2363 apic->lapic_timer.tscdeadline = data;
2364 start_apic_timer(apic);
2367 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2369 apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2372 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2376 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2378 return (tpr & 0xf0) >> 4;
2381 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2383 u64 old_value = vcpu->arch.apic_base;
2384 struct kvm_lapic *apic = vcpu->arch.apic;
2386 vcpu->arch.apic_base = value;
2388 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2389 kvm_update_cpuid_runtime(vcpu);
2394 /* update jump label if enable bit changes */
2395 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2396 if (value & MSR_IA32_APICBASE_ENABLE) {
2397 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2398 static_branch_slow_dec_deferred(&apic_hw_disabled);
2399 /* Check if there are APF page ready requests pending */
2400 kvm_make_request(KVM_REQ_APF_READY, vcpu);
2402 static_branch_inc(&apic_hw_disabled.key);
2403 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2407 if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
2408 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2410 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
2411 kvm_vcpu_update_apicv(vcpu);
2412 static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
2415 apic->base_address = apic->vcpu->arch.apic_base &
2416 MSR_IA32_APICBASE_BASE;
2418 if ((value & MSR_IA32_APICBASE_ENABLE) &&
2419 apic->base_address != APIC_DEFAULT_PHYS_BASE) {
2420 kvm_set_apicv_inhibit(apic->vcpu->kvm,
2421 APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
2425 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2427 struct kvm_lapic *apic = vcpu->arch.apic;
2429 if (apic->apicv_active) {
2430 /* irr_pending is always true when apicv is activated. */
2431 apic->irr_pending = true;
2432 apic->isr_count = 1;
2435 * Don't clear irr_pending, searching the IRR can race with
2436 * updates from the CPU as APICv is still active from hardware's
2437 * perspective. The flag will be cleared as appropriate when
2438 * KVM injects the interrupt.
2440 apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2442 apic->highest_isr_cache = -1;
2444 EXPORT_SYMBOL_GPL(kvm_apic_update_apicv);
2446 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2448 struct kvm_lapic *apic = vcpu->arch.apic;
2452 static_call_cond(kvm_x86_apicv_pre_state_restore)(vcpu);
2455 msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
2456 if (kvm_vcpu_is_reset_bsp(vcpu))
2457 msr_val |= MSR_IA32_APICBASE_BSP;
2458 kvm_lapic_set_base(vcpu, msr_val);
2464 /* Stop the timer in case it's a reset to an active apic */
2465 hrtimer_cancel(&apic->lapic_timer.timer);
2467 /* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2469 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2470 kvm_apic_set_version(apic->vcpu);
2472 for (i = 0; i < apic->nr_lvt_entries; i++)
2473 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
2474 apic_update_lvtt(apic);
2475 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2476 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2477 kvm_lapic_set_reg(apic, APIC_LVT0,
2478 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2479 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2481 kvm_apic_set_dfr(apic, 0xffffffffU);
2482 apic_set_spiv(apic, 0xff);
2483 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2484 if (!apic_x2apic_mode(apic))
2485 kvm_apic_set_ldr(apic, 0);
2486 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2487 if (!apic_x2apic_mode(apic)) {
2488 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2489 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2491 kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2493 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2494 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2495 for (i = 0; i < 8; i++) {
2496 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2497 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2498 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2500 kvm_apic_update_apicv(vcpu);
2501 update_divide_count(apic);
2502 atomic_set(&apic->lapic_timer.pending, 0);
2504 vcpu->arch.pv_eoi.msr_val = 0;
2505 apic_update_ppr(apic);
2506 if (apic->apicv_active) {
2507 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2508 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2509 static_call_cond(kvm_x86_hwapic_isr_update)(-1);
2512 vcpu->arch.apic_arb_prio = 0;
2513 vcpu->arch.apic_attention = 0;
2515 kvm_recalculate_apic_map(vcpu->kvm);
2519 *----------------------------------------------------------------------
2521 *----------------------------------------------------------------------
2524 static bool lapic_is_periodic(struct kvm_lapic *apic)
2526 return apic_lvtt_period(apic);
2529 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2531 struct kvm_lapic *apic = vcpu->arch.apic;
2533 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2534 return atomic_read(&apic->lapic_timer.pending);
2539 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2541 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2542 int vector, mode, trig_mode;
2545 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2546 vector = reg & APIC_VECTOR_MASK;
2547 mode = reg & APIC_MODE_MASK;
2548 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2550 r = __apic_accept_irq(apic, mode, vector, 1, trig_mode, NULL);
2551 if (r && lvt_type == APIC_LVTPC &&
2552 guest_cpuid_is_intel_compatible(apic->vcpu))
2553 kvm_lapic_set_reg(apic, APIC_LVTPC, reg | APIC_LVT_MASKED);
2559 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2561 struct kvm_lapic *apic = vcpu->arch.apic;
2564 kvm_apic_local_deliver(apic, APIC_LVT0);
2567 static const struct kvm_io_device_ops apic_mmio_ops = {
2568 .read = apic_mmio_read,
2569 .write = apic_mmio_write,
2572 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2574 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2575 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2577 apic_timer_expired(apic, true);
2579 if (lapic_is_periodic(apic)) {
2580 advance_periodic_target_expiration(apic);
2581 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2582 return HRTIMER_RESTART;
2584 return HRTIMER_NORESTART;
2587 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2589 struct kvm_lapic *apic;
2591 ASSERT(vcpu != NULL);
2593 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2597 vcpu->arch.apic = apic;
2599 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2601 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2603 goto nomem_free_apic;
2607 apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
2609 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2610 HRTIMER_MODE_ABS_HARD);
2611 apic->lapic_timer.timer.function = apic_timer_fn;
2612 if (timer_advance_ns == -1) {
2613 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2614 lapic_timer_advance_dynamic = true;
2616 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2617 lapic_timer_advance_dynamic = false;
2621 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2622 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2624 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2625 static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2626 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2631 vcpu->arch.apic = NULL;
2636 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2638 struct kvm_lapic *apic = vcpu->arch.apic;
2641 if (!kvm_apic_present(vcpu))
2644 __apic_update_ppr(apic, &ppr);
2645 return apic_has_interrupt_for_ppr(apic, ppr);
2647 EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2649 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2651 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2653 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2655 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2656 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2661 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2663 struct kvm_lapic *apic = vcpu->arch.apic;
2665 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2666 kvm_apic_inject_pending_timer_irqs(apic);
2667 atomic_set(&apic->lapic_timer.pending, 0);
2671 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2673 int vector = kvm_apic_has_interrupt(vcpu);
2674 struct kvm_lapic *apic = vcpu->arch.apic;
2681 * We get here even with APIC virtualization enabled, if doing
2682 * nested virtualization and L1 runs with the "acknowledge interrupt
2683 * on exit" mode. Then we cannot inject the interrupt via RVI,
2684 * because the process would deliver it through the IDT.
2687 apic_clear_irr(vector, apic);
2688 if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
2690 * For auto-EOI interrupts, there might be another pending
2691 * interrupt above PPR, so check whether to raise another
2694 apic_update_ppr(apic);
2697 * For normal interrupts, PPR has been raised and there cannot
2698 * be a higher-priority pending interrupt---except if there was
2699 * a concurrent interrupt injection, but that would have
2700 * triggered KVM_REQ_EVENT already.
2702 apic_set_isr(vector, apic);
2703 __apic_update_ppr(apic, &ppr);
2709 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2710 struct kvm_lapic_state *s, bool set)
2712 if (apic_x2apic_mode(vcpu->arch.apic)) {
2713 u32 *id = (u32 *)(s->regs + APIC_ID);
2714 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2717 if (vcpu->kvm->arch.x2apic_format) {
2718 if (*id != vcpu->vcpu_id)
2728 * In x2APIC mode, the LDR is fixed and based on the id. And
2729 * ICR is internally a single 64-bit register, but needs to be
2730 * split to ICR+ICR2 in userspace for backwards compatibility.
2733 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2735 icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
2736 (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
2737 __kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
2739 icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
2740 __kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
2747 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2749 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2752 * Get calculated timer current count for remaining timer period (if
2753 * any) and store it in the returned register set.
2755 __kvm_lapic_set_reg(s->regs, APIC_TMCCT,
2756 __apic_read(vcpu->arch.apic, APIC_TMCCT));
2758 return kvm_apic_state_fixup(vcpu, s, false);
2761 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2763 struct kvm_lapic *apic = vcpu->arch.apic;
2766 static_call_cond(kvm_x86_apicv_pre_state_restore)(vcpu);
2768 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2769 /* set SPIV separately to get count of SW disabled APICs right */
2770 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2772 r = kvm_apic_state_fixup(vcpu, s, true);
2774 kvm_recalculate_apic_map(vcpu->kvm);
2777 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2779 if (!apic_x2apic_mode(apic))
2780 kvm_lapic_xapic_id_updated(apic);
2782 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2783 kvm_recalculate_apic_map(vcpu->kvm);
2784 kvm_apic_set_version(vcpu);
2786 apic_update_ppr(apic);
2787 cancel_apic_timer(apic);
2788 apic->lapic_timer.expired_tscdeadline = 0;
2789 apic_update_lvtt(apic);
2790 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2791 update_divide_count(apic);
2792 __start_apic_timer(apic, APIC_TMCCT);
2793 kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
2794 kvm_apic_update_apicv(vcpu);
2795 if (apic->apicv_active) {
2796 static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2797 static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
2798 static_call_cond(kvm_x86_hwapic_isr_update)(apic_find_highest_isr(apic));
2800 kvm_make_request(KVM_REQ_EVENT, vcpu);
2801 if (ioapic_in_kernel(vcpu->kvm))
2802 kvm_rtc_eoi_tracking_restore_one(vcpu);
2804 vcpu->arch.apic_arb_prio = 0;
2809 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2811 struct hrtimer *timer;
2813 if (!lapic_in_kernel(vcpu) ||
2814 kvm_can_post_timer_interrupt(vcpu))
2817 timer = &vcpu->arch.apic->lapic_timer.timer;
2818 if (hrtimer_cancel(timer))
2819 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2823 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2825 * Detect whether guest triggered PV EOI since the
2826 * last entry. If yes, set EOI on guests's behalf.
2827 * Clear PV EOI in guest memory in any case.
2829 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2830 struct kvm_lapic *apic)
2834 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2835 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2837 * KVM_APIC_PV_EOI_PENDING is unset:
2838 * -> host disabled PV EOI.
2839 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2840 * -> host enabled PV EOI, guest did not execute EOI yet.
2841 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2842 * -> host enabled PV EOI, guest executed EOI.
2844 BUG_ON(!pv_eoi_enabled(vcpu));
2846 if (pv_eoi_test_and_clr_pending(vcpu))
2848 vector = apic_set_eoi(apic);
2849 trace_kvm_pv_eoi(apic, vector);
2852 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2856 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2857 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2859 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2862 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2866 apic_set_tpr(vcpu->arch.apic, data & 0xff);
2870 * apic_sync_pv_eoi_to_guest - called before vmentry
2872 * Detect whether it's safe to enable PV EOI and
2875 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2876 struct kvm_lapic *apic)
2878 if (!pv_eoi_enabled(vcpu) ||
2879 /* IRR set or many bits in ISR: could be nested. */
2880 apic->irr_pending ||
2881 /* Cache not set: could be safe but we don't bother. */
2882 apic->highest_isr_cache == -1 ||
2883 /* Need EOI to update ioapic. */
2884 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2886 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2887 * so we need not do anything here.
2892 pv_eoi_set_pending(apic->vcpu);
2895 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2898 int max_irr, max_isr;
2899 struct kvm_lapic *apic = vcpu->arch.apic;
2901 apic_sync_pv_eoi_to_guest(vcpu, apic);
2903 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2906 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2907 max_irr = apic_find_highest_irr(apic);
2910 max_isr = apic_find_highest_isr(apic);
2913 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2915 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2919 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2922 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2923 &vcpu->arch.apic->vapic_cache,
2924 vapic_addr, sizeof(u32)))
2926 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2928 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2931 vcpu->arch.apic->vapic_addr = vapic_addr;
2935 int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
2937 data &= ~APIC_ICR_BUSY;
2939 kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
2940 kvm_lapic_set_reg64(apic, APIC_ICR, data);
2941 trace_kvm_apic_write(APIC_ICR, data);
2945 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
2949 if (reg == APIC_ICR) {
2950 *data = kvm_lapic_get_reg64(apic, APIC_ICR);
2954 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2962 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
2965 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
2966 * can be written as such, all other registers remain accessible only
2967 * through 32-bit reads/writes.
2969 if (reg == APIC_ICR)
2970 return kvm_x2apic_icr_write(apic, data);
2972 /* Bits 63:32 are reserved in all other registers. */
2976 return kvm_lapic_reg_write(apic, reg, (u32)data);
2979 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2981 struct kvm_lapic *apic = vcpu->arch.apic;
2982 u32 reg = (msr - APIC_BASE_MSR) << 4;
2984 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2987 return kvm_lapic_msr_write(apic, reg, data);
2990 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2992 struct kvm_lapic *apic = vcpu->arch.apic;
2993 u32 reg = (msr - APIC_BASE_MSR) << 4;
2995 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2998 if (reg == APIC_DFR)
3001 return kvm_lapic_msr_read(apic, reg, data);
3004 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
3006 if (!lapic_in_kernel(vcpu))
3009 return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
3012 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
3014 if (!lapic_in_kernel(vcpu))
3017 return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
3020 int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
3022 u64 addr = data & ~KVM_MSR_ENABLED;
3023 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3024 unsigned long new_len;
3027 if (!IS_ALIGNED(addr, 4))
3030 if (data & KVM_MSR_ENABLED) {
3031 if (addr == ghc->gpa && len <= ghc->len)
3036 ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
3041 vcpu->arch.pv_eoi.msr_val = data;
3046 int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
3048 struct kvm_lapic *apic = vcpu->arch.apic;
3052 if (!kvm_apic_has_pending_init_or_sipi(vcpu))
3055 if (is_guest_mode(vcpu)) {
3056 r = kvm_check_nested_events(vcpu);
3058 return r == -EBUSY ? 0 : r;
3060 * Continue processing INIT/SIPI even if a nested VM-Exit
3061 * occurred, e.g. pending SIPIs should be dropped if INIT+SIPI
3062 * are blocked as a result of transitioning to VMX root mode.
3067 * INITs are blocked while CPU is in specific states (SMM, VMX root
3068 * mode, SVM with GIF=0), while SIPIs are dropped if the CPU isn't in
3069 * wait-for-SIPI (WFS).
3071 if (!kvm_apic_init_sipi_allowed(vcpu)) {
3072 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
3073 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
3077 if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
3078 kvm_vcpu_reset(vcpu, true);
3079 if (kvm_vcpu_is_bsp(apic->vcpu))
3080 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3082 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
3084 if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
3085 if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
3086 /* evaluate pending_events before reading the vector */
3088 sipi_vector = apic->sipi_vector;
3089 static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
3090 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3096 void kvm_lapic_exit(void)
3098 static_key_deferred_flush(&apic_hw_disabled);
3099 WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3100 static_key_deferred_flush(&apic_sw_disabled);
3101 WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));